Optional, default regex pattern is (app.kubernetes.io/(?!part-of).|</sup>kustomize.toolkit.fluxcd.io.)</code>.
The regex exclusion pattern used to filter labels propagation from the main custom resource to its subresources.
The labels exclusion filter is not applied to labels in template sections such as spec.kafka.template.pod.metadata.labels
.</p>
env:
- name: STRIMZI_LABELS_EXCLUSION_PATTERN
value: "^key1.*"
</dd>
STRIMZI_CUSTOM_<COMPONENT_NAME>_LABELS
Optional.
One or more custom labels to apply to all the pods created by the custom resource of the component.
The Cluster Operator labels the pods when the custom resource is created or is next reconciled.
Labels can be applied to the following components:
-
KAFKA
-
KAFKA_CONNECT
-
KAFKA_CONNECT_BUILD
-
ZOOKEEPER
-
ENTITY_OPERATOR
-
KAFKA_MIRROR_MAKER2
-
KAFKA_MIRROR_MAKER
-
CRUISE_CONTROL
-
KAFKA_BRIDGE
-
KAFKA_EXPORTER
STRIMZI_CUSTOM_RESOURCE_SELECTOR
Optional.
The label selector to filter the custom resources handled by the Cluster Operator.
The operator will operate only on those custom resources that have the specified labels set.
Resources without these labels will not be seen by the operator.
The label selector applies to Kafka
, KafkaConnect
, KafkaBridge
, KafkaMirrorMaker
, and KafkaMirrorMaker2
resources.
KafkaRebalance
and KafkaConnector
resources are operated only when their corresponding Kafka and Kafka Connect clusters have the matching labels.
env:
- name: STRIMZI_CUSTOM_RESOURCE_SELECTOR
value: label1=value1,label2=value2
STRIMZI_KAFKA_IMAGES
Required.
The mapping from the Kafka version to the corresponding image containing a Kafka broker for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.43.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
STRIMZI_KAFKA_CONNECT_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of Kafka Connect for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.43.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
STRIMZI_KAFKA_MIRROR_MAKER2_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of MirrorMaker 2 for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.43.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
(Deprecated) STRIMZI_KAFKA_MIRROR_MAKER_IMAGES
Required.
The mapping from the Kafka version to the corresponding image of MirrorMaker for that version.
For example 3.7.0=quay.io/strimzi/kafka:0.43.0-kafka-3.7.0, 3.8.0=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE
Optional.
The default is quay.io/strimzi/operator:0.43.0
.
The image name to use as the default when deploying the Topic Operator
if no image is specified as the Kafka.spec.entityOperator.topicOperator.image
in the Kafka
resource.
STRIMZI_DEFAULT_USER_OPERATOR_IMAGE
Optional.
The default is quay.io/strimzi/operator:0.43.0
.
The image name to use as the default when deploying the User Operator
if no image is specified as the Kafka.spec.entityOperator.userOperator.image
in the Kafka
resource.
STRIMZI_DEFAULT_KAFKA_EXPORTER_IMAGE
Optional.
The default is quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
The image name to use as the default when deploying the Kafka Exporter if no image is specified as the Kafka.spec.kafkaExporter.image
in the Kafka
resource.
STRIMZI_DEFAULT_CRUISE_CONTROL_IMAGE
Optional.
The default is quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
.
The image name to use as the default when deploying Cruise Control if no image is specified as the Kafka.spec.cruiseControl.image
in the Kafka
resource.
STRIMZI_DEFAULT_KAFKA_BRIDGE_IMAGE
Optional.
The default is quay.io/strimzi/kafka-bridge:0.30.0
.
The image name to use as the default when deploying the Kafka Bridge if no image is specified as the Kafka.spec.kafkaBridge.image
in the Kafka
resource.
STRIMZI_DEFAULT_KAFKA_INIT_IMAGE
Optional.
The default is quay.io/strimzi/operator:0.43.0
.
The image name to use as the default for the Kafka initializer container if no image is specified in the brokerRackInitImage
of the Kafka
resource or the clientRackInitImage
of the Kafka Connect resource.
The init container is started before the Kafka cluster for initial configuration work, such as rack support.
STRIMZI_IMAGE_PULL_POLICY
Optional.
The ImagePullPolicy
that is applied to containers in all pods managed by the Cluster Operator.
The valid values are Always
, IfNotPresent
, and Never
.
If not specified, the Kubernetes defaults are used.
Changing the policy will result in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.
STRIMZI_IMAGE_PULL_SECRETS
Optional.
A comma-separated list of Secret
names.
The secrets referenced here contain the credentials to the container registries where the container images are pulled from.
The secrets are specified in the imagePullSecrets
property for all pods created by the Cluster Operator.
Changing this list results in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.
STRIMZI_KUBERNETES_VERSION
Optional.
Overrides the Kubernetes version information detected from the API server.
Example configuration for Kubernetes version override
env:
- name: STRIMZI_KUBERNETES_VERSION
value: |
major=1
minor=16
gitVersion=v1.16.2
gitCommit=c97fe5036ef3df2967d086711e6c0c405941e14b
gitTreeState=clean
buildDate=2019-10-15T19:09:08Z
goVersion=go1.12.10
compiler=gc
platform=linux/amd64
KUBERNETES_SERVICE_DNS_DOMAIN
Optional.
Overrides the default Kubernetes DNS domain name suffix.
By default, services assigned in the Kubernetes cluster have a DNS domain name that uses the default suffix cluster.local
.
For example, for broker kafka-0:
<cluster-name>-kafka-0.<cluster-name>-kafka-brokers.<namespace>.svc.cluster.local
The DNS domain name is added to the Kafka broker certificates used for hostname verification.
If you are using a different DNS domain name suffix in your cluster, change the KUBERNETES_SERVICE_DNS_DOMAIN
environment variable from the default to the one you are using in order to establish a connection with the Kafka brokers.
STRIMZI_CONNECT_BUILD_TIMEOUT_MS
Optional, default 300000 ms.
The timeout for building new Kafka Connect images with additional connectors, in milliseconds.
Consider increasing this value when using Strimzi to build container images containing many connectors or using a slow container registry.
STRIMZI_NETWORK_POLICY_GENERATION
Optional, default true
.
Network policy for resources.
Network policies allow connections between Kafka components.
Set this environment variable to false
to disable network policy generation. You might do this, for example, if you want to use custom network policies. Custom network policies allow more control over maintaining the connections between components.
STRIMZI_DNS_CACHE_TTL
Optional, default 30
.
Number of seconds to cache successful name lookups in local DNS resolver. Any negative value means cache forever. Zero means do not cache, which can be useful for avoiding connection errors due to long caching policies being applied.
STRIMZI_POD_SET_RECONCILIATION_ONLY
Optional, default false
.
When set to true
, the Cluster Operator reconciles only the StrimziPodSet
resources and any changes to the other custom resources (Kafka
, KafkaConnect
, and so on) are ignored.
This mode is useful for ensuring that your pods are recreated if needed, but no other changes happen to the clusters.
STRIMZI_FEATURE_GATES
Optional.
Enables or disables the features and functionality controlled by feature gates.
STRIMZI_POD_SECURITY_PROVIDER_CLASS
Optional.
Configuration for the pluggable PodSecurityProvider
class, which can be used to provide the security context configuration for Pods and containers.
</dl>
</div>
Use the STRIMZI_OPERATOR_NAMESPACE_LABELS
environment variable to establish network policy for the Cluster Operator using namespace labels.
The Cluster Operator can run in the same namespace as the resources it manages, or in a separate namespace.
By default, the STRIMZI_OPERATOR_NAMESPACE
environment variable is configured to use the downward API to find the namespace the Cluster Operator is running in.
If the Cluster Operator is running in the same namespace as the resources, only local access is required and allowed by Strimzi.
If the Cluster Operator is running in a separate namespace to the resources it manages, any namespace in the Kubernetes cluster is allowed access to the Cluster Operator unless network policy is configured.
By adding namespace labels, access to the Cluster Operator is restricted to the namespaces specified.
Network policy configured for the Cluster Operator deployment
#...
env:
# ...
- name: STRIMZI_OPERATOR_NAMESPACE_LABELS
value: label1=value1,label2=value2
#...
Use the STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
variable to set the time interval for periodic reconciliations by the Cluster Operator.
Replace its value with the required interval in milliseconds.
Reconciliation period configured for the Cluster Operator deployment
#...
env:
# ...
- name: STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
value: "120000"
#...
The Cluster Operator reacts to all notifications about applicable cluster resources received from the Kubernetes cluster.
If the operator is not running, or if a notification is not received for any reason, resources will get out of sync with the state of the running Kubernetes cluster.
In order to handle failovers properly, a periodic reconciliation process is executed by the Cluster Operator so that it can compare the state of the resources with the current cluster deployments in order to have a consistent state across all of them.
Sometimes it is useful to pause the reconciliation of custom resources managed by Strimzi operators,
so that you can perform fixes or make updates.
If reconciliations are paused, any changes made to custom resources are ignored by the operators until the pause ends.
If you want to pause reconciliation of a custom resource, set the strimzi.io/pause-reconciliation
annotation to true
in its configuration.
This instructs the appropriate operator to pause reconciliation of the custom resource.
For example, you can apply the annotation to the KafkaConnect
resource so that reconciliation by the Cluster Operator is paused.
You can also create a custom resource with the pause annotation enabled.
The custom resource is created, but it is ignored.
Procedure
-
Annotate the custom resource in Kubernetes, setting pause-reconciliation
to true
:
kubectl annotate <kind_of_custom_resource> <name_of_custom_resource> strimzi.io/pause-reconciliation="true"
For example, for the KafkaConnect
custom resource:
kubectl annotate KafkaConnect my-connect strimzi.io/pause-reconciliation="true"
-
Check that the status conditions of the custom resource show a change to ReconciliationPaused
:
kubectl describe <kind_of_custom_resource> <name_of_custom_resource>
The type
condition changes to ReconciliationPaused
at the lastTransitionTime
.
Example custom resource with a paused reconciliation condition type
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
annotations:
strimzi.io/pause-reconciliation: "true"
strimzi.io/use-connector-resources: "true"
creationTimestamp: 2021-03-12T10:47:11Z
#...
spec:
# ...
status:
conditions:
- lastTransitionTime: 2021-03-12T10:47:41.689249Z
status: "True"
type: ReconciliationPaused
The default Cluster Operator configuration enables leader election to run multiple parallel replicas of the Cluster Operator.
One replica is elected as the active leader and operates the deployed resources.
The other replicas run in standby mode.
When the leader stops or fails, one of the standby replicas is elected as the new leader and starts operating the deployed resources.
By default, Strimzi runs with a single Cluster Operator replica that is always the leader replica.
When a single Cluster Operator replica stops or fails, Kubernetes starts a new replica.
Running the Cluster Operator with multiple replicas is not essential.
But it’s useful to have replicas on standby in case of large-scale disruptions caused by major failure.
For example, suppose multiple worker nodes or an entire availability zone fails.
This failure might cause the Cluster Operator pod and many Kafka pods to go down at the same time.
If subsequent pod scheduling causes congestion through lack of resources, this can delay operations when running a single Cluster Operator.
Configure leader election environment variables when running additional Cluster Operator replicas.
The following environment variables are supported:
STRIMZI_LEADER_ELECTION_ENABLED
-
Optional, disabled (false
) by default.
Enables or disables leader election, which allows additional Cluster Operator replicas to run on standby.
Note
|
Leader election is disabled by default.
It is only enabled when applying this environment variable on installation.
|
STRIMZI_LEADER_ELECTION_LEASE_NAME
-
Required when leader election is enabled.
The name of the Kubernetes Lease
resource that is used for the leader election.
STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE
-
Required when leader election is enabled.
The namespace where the Kubernetes Lease
resource used for leader election is created.
You can use the downward API to configure it to the namespace where the Cluster Operator is deployed.
env:
- name: STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
STRIMZI_LEADER_ELECTION_IDENTITY
-
Required when leader election is enabled.
Configures the identity of a given Cluster Operator instance used during the leader election.
The identity must be unique for each operator instance.
You can use the downward API to configure it to the name of the pod where the Cluster Operator is deployed.
env:
- name: STRIMZI_LEADER_ELECTION_IDENTITY
valueFrom:
fieldRef:
fieldPath: metadata.name
STRIMZI_LEADER_ELECTION_LEASE_DURATION_MS
-
Optional, default 15000 ms.
Specifies the duration the acquired lease is valid.
STRIMZI_LEADER_ELECTION_RENEW_DEADLINE_MS
-
Optional, default 10000 ms.
Specifies the period the leader should try to maintain leadership.
STRIMZI_LEADER_ELECTION_RETRY_PERIOD_MS
-
Optional, default 2000 ms.
Specifies the frequency of updates to the lease lock by the leader.
To run additional Cluster Operator replicas in standby mode, you will need to increase the number of replicas and enable leader election.
To configure leader election, use the leader election environment variables.
To make the required changes, configure the following Cluster Operator installation files located in install/cluster-operator/
:
-
060-Deployment-strimzi-cluster-operator.yaml
-
022-ClusterRole-strimzi-cluster-operator-role.yaml
-
022-RoleBinding-strimzi-cluster-operator.yaml
Leader election has its own ClusterRole
and RoleBinding
RBAC resources that target the namespace where the Cluster Operator is running, rather than the namespace it is watching.
The default deployment configuration creates a Lease
resource called strimzi-cluster-operator
in the same namespace as the Cluster Operator.
The Cluster Operator uses leases to manage leader election.
The RBAC resources provide the permissions to use the Lease
resource.
If you use a different Lease
name or namespace, update the ClusterRole
and RoleBinding
files accordingly.
Procedure
Edit the Deployment
resource that is used to deploy the Cluster Operator, which is defined in the 060-Deployment-strimzi-cluster-operator.yaml
file.
-
Change the replicas
property from the default (1) to a value that matches the required number of replicas.
Increasing the number of Cluster Operator replicas
apiVersion: apps/v1
kind: Deployment
metadata:
name: strimzi-cluster-operator
labels:
app: strimzi
spec:
replicas: 3
-
Check that the leader election env
properties are set.
If they are not set, configure them.
To enable leader election, STRIMZI_LEADER_ELECTION_ENABLED
must be set to true
(default).
In this example, the name of the lease is changed to my-strimzi-cluster-operator
.
Configuring leader election environment variables for the Cluster Operator
# ...
spec
containers:
- name: strimzi-cluster-operator
# ...
env:
- name: STRIMZI_LEADER_ELECTION_ENABLED
value: "true"
- name: STRIMZI_LEADER_ELECTION_LEASE_NAME
value: "my-strimzi-cluster-operator"
- name: STRIMZI_LEADER_ELECTION_LEASE_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STRIMZI_LEADER_ELECTION_IDENTITY
valueFrom:
fieldRef:
fieldPath: metadata.name
If you specified a different name or namespace for the Lease
resource used in leader election, update the RBAC resources.
-
(optional) Edit the ClusterRole
resource in the 022-ClusterRole-strimzi-cluster-operator-role.yaml
file.
Update resourceNames
with the name of the Lease
resource.
Updating the ClusterRole references to the lease
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: strimzi-cluster-operator-leader-election
labels:
app: strimzi
rules:
- apiGroups:
- coordination.k8s.io
resourceNames:
- my-strimzi-cluster-operator
# ...
-
(optional) Edit the RoleBinding
resource in the 022-RoleBinding-strimzi-cluster-operator.yaml
file.
Update subjects.name
and subjects.namespace
with the name of the Lease
resource and the namespace where it was created.
Updating the RoleBinding references to the lease
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: strimzi-cluster-operator-leader-election
labels:
app: strimzi
subjects:
- kind: ServiceAccount
name: my-strimzi-cluster-operator
namespace: myproject
# ...
-
Deploy the Cluster Operator:
kubectl create -f install/cluster-operator -n myproject
-
Check the status of the deployment:
kubectl get deployments -n myproject
Output shows the deployment name and readiness
NAME READY UP-TO-DATE AVAILABLE
strimzi-cluster-operator 3/3 3 3
READY
shows the number of replicas that are ready/expected.
The deployment is successful when the AVAILABLE
output shows the correct number of replicas.
If you are running a Kafka cluster behind a HTTP proxy, you can still pass data in and out of the cluster.
For example, you can run Kafka Connect with connectors that push and pull data from outside the proxy.
Or you can use a proxy to connect with an authorization server.
Configure the Cluster Operator deployment to specify the proxy environment variables.
The Cluster Operator accepts standard proxy configuration (HTTP_PROXY
, HTTPS_PROXY
and NO_PROXY
) as environment variables.
The proxy settings are applied to all Strimzi containers.
The format for a proxy address is http://<ip_address>:<port_number>.
To set up a proxy with a name and password, the format is http://<username>:<password>@<ip-address>:<port_number>.
Procedure
-
To add proxy environment variables to the Cluster Operator, update its Deployment
configuration (install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
).
Example proxy configuration for the Cluster Operator
apiVersion: apps/v1
kind: Deployment
spec:
# ...
template:
spec:
serviceAccountName: strimzi-cluster-operator
containers:
# ...
env:
# ...
- name: "HTTP_PROXY"
value: "http://proxy.com" (1)
- name: "HTTPS_PROXY"
value: "https://proxy.com" (2)
- name: "NO_PROXY"
value: "internal.com, other.domain.com" (3)
# ...
-
Address of the proxy server.
-
Secure address of the proxy server.
-
Addresses for servers that are accessed directly as exceptions to the proxy server. The URLs are comma-separated.
Alternatively, edit the Deployment
directly:
kubectl edit deployment strimzi-cluster-operator
-
If you updated the YAML file instead of editing the Deployment
directly, apply the changes:
kubectl create -f install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
Strimzi automatically switches to FIPS mode when running on a FIPS-enabled Kubernetes cluster.
Disable FIPS mode by setting the FIPS_MODE
environment variable to disabled
in the deployment configuration for the Cluster Operator.
With FIPS mode disabled, Strimzi automatically disables FIPS in the OpenJDK for all components.
With FIPS mode disabled, Strimzi is not FIPS compliant.
The Strimzi operators, as well as all operands, run in the same way as if they were running on an Kubernetes cluster without FIPS enabled.
Procedure
-
To disable the FIPS mode in the Cluster Operator, update its Deployment
configuration (install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
) and add the FIPS_MODE
environment variable.
Example FIPS configuration for the Cluster Operator
apiVersion: apps/v1
kind: Deployment
spec:
# ...
template:
spec:
serviceAccountName: strimzi-cluster-operator
containers:
# ...
env:
# ...
- name: "FIPS_MODE"
value: "disabled" # (1)
# ...
Alternatively, edit the Deployment
directly:
kubectl edit deployment strimzi-cluster-operator
-
If you updated the YAML file instead of editing the Deployment
directly, apply the changes:
kubectl apply -f install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
</div>
Update the spec
properties of the KafkaConnect
custom resource to configure your Kafka Connect deployment.
Use Kafka Connect to set up external data connections to your Kafka cluster.
Use the properties of the KafkaConnect
resource to configure your Kafka Connect deployment.
KafkaConnector configuration
KafkaConnector
resources allow you to create and manage connector instances for Kafka Connect in a Kubernetes-native way.
In your Kafka Connect configuration, you enable KafkaConnectors for a Kafka Connect cluster by adding the strimzi.io/use-connector-resources
annotation.
You can also add a build
configuration so that Strimzi automatically builds a container image with the connector plugins you require for your data connections.
External configuration for Kafka Connect connectors is specified through the externalConfiguration
property.
To manage connectors, you can use use KafkaConnector
custom resources or the Kafka Connect REST API.
KafkaConnector
resources must be deployed to the same namespace as the Kafka Connect cluster they link to.
For more information on using these methods to create, reconfigure, or delete connectors, see Adding connectors.
Connector configuration is passed to Kafka Connect as part of an HTTP request and stored within Kafka itself.
ConfigMaps and Secrets are standard Kubernetes resources used for storing configurations and confidential data.
You can use ConfigMaps and Secrets to configure certain elements of a connector.
You can then reference the configuration values in HTTP REST commands, which keeps the configuration separate and more secure, if needed.
This method applies especially to confidential data, such as usernames, passwords, or certificates.
Example KafkaConnect
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect # (1)
metadata:
name: my-connect-cluster
annotations:
strimzi.io/use-connector-resources: "true" # (2)
# Deployment specifications
spec:
# Replicas (required)
replicas: 3 # (3)
# Authentication (optional)
authentication: # (4)
type: tls
certificateAndKey:
certificate: source.crt
key: source.key
secretName: my-user-source
# Bootstrap servers (required)
bootstrapServers: my-cluster-kafka-bootstrap:9092 # (5)
# TLS configuration (optional)
tls: # (6)
trustedCertificates:
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
# Kafka Connect configuration (recommended)
config: # (7)
group.id: my-connect-cluster
offset.storage.topic: my-connect-cluster-offsets
config.storage.topic: my-connect-cluster-configs
status.storage.topic: my-connect-cluster-status
key.converter: org.apache.kafka.connect.json.JsonConverter
value.converter: org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable: true
value.converter.schemas.enable: true
config.storage.replication.factor: 3
offset.storage.replication.factor: 3
status.storage.replication.factor: 3
# Build configuration (optional)
build: # (8)
output: # (9)
type: docker
image: my-registry.io/my-org/my-connect-cluster:latest
pushSecret: my-registry-credentials
plugins: # (10)
- name: connector-1
artifacts:
- type: tgz
url: <url_to_download_connector_1_artifact>
sha512sum: <SHA-512_checksum_of_connector_1_artifact>
- name: connector-2
artifacts:
- type: jar
url: <url_to_download_connector_2_artifact>
sha512sum: <SHA-512_checksum_of_connector_2_artifact>
# External configuration (optional)
externalConfiguration: # (11)
env:
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: aws-creds
key: awsAccessKey
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-creds
key: awsSecretAccessKey
# Resources requests and limits (recommended)
resources: # (12)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# Logging configuration (optional)
logging: # (13)
type: inline
loggers:
log4j.rootLogger: INFO
# Readiness probe (optional)
readinessProbe: # (14)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# Metrics configuration (optional)
metricsConfig: # (15)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-key
# JVM options (optional)
jvmOptions: # (16)
"-Xmx": "1g"
"-Xms": "1g"
# Custom image (optional)
image: my-org/my-image:latest # (17)
# Rack awareness (optional)
rack:
topologyKey: topology.kubernetes.io/zone # (18)
# Pod template (optional)
template: # (19)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
connectContainer: # (20)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
# Tracing configuration (optional)
tracing:
type: opentelemetry # (21)
-
Use KafkaConnect
.
-
Enables KafkaConnectors for the Kafka Connect cluster.
-
The number of replica nodes for the workers that run tasks.
-
Authentication for the Kafka Connect cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
By default, Kafka Connect connects to Kafka brokers using a plain text connection.
-
Bootstrap server for connection to the Kafka cluster.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Kafka Connect configuration of workers (not connectors).
Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.
-
Build configuration properties for building a container image with connector plugins automatically.
-
(Required) Configuration of the container registry where new images are pushed.
-
(Required) List of connector plugins and their artifacts to add to the new container image. Each plugin must be configured with at least one artifact
.
-
External configuration for connectors using environment variables, as shown here, or volumes.
You can also use configuration provider plugins to load configuration values from external sources.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified Kafka Connect loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Connect log4j.rootLogger
logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
Prometheus metrics, which are enabled by referencing a ConfigMap containing configuration for the Prometheus JMX exporter in this example. You can enable metrics without further configuration using a reference to a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key
.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka Connect.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
SPECIALIZED OPTION: Rack awareness configuration for the deployment. This is a specialized option intended for a deployment within the same location, not across regions. Use this option if you want connectors to consume from the closest replica rather than the leader replica. In certain cases, consuming from the closest replica can improve network utilization or reduce costs . The topologyKey
must match a node label containing the rack ID. The example used in this configuration specifies a zone using the standard topology.kubernetes.io/zone
label. To consume from the closest replica, enable the RackAwareReplicaSelector
in the Kafka broker configuration.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
By default, Strimzi configures the group ID and names of the internal topics used by Kafka Connect.
When running multiple instances of Kafka Connect, you must change these default settings using the following config
properties:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
config:
group.id: my-connect-cluster # (1)
offset.storage.topic: my-connect-cluster-offsets # (2)
config.storage.topic: my-connect-cluster-configs # (3)
status.storage.topic: my-connect-cluster-status # (4)
# ...
# ...
-
The Kafka Connect cluster group ID within Kafka.
-
Kafka topic that stores connector offsets.
-
Kafka topic that stores connector and task status configurations.
-
Kafka topic that stores connector and task status updates.
Note
|
Values for the three topics must be the same for all instances with the same group.id .
|
Unless you modify these default settings, each instance connecting to the same Kafka cluster is deployed with the same values.
In practice, this means all instances form a cluster and use the same internal topics.
Multiple instances attempting to use the same internal topics will cause unexpected errors, so you must change the values of these properties for each instance.
When using authorization in Kafka, a Kafka Connect user requires read/write access to the cluster group and internal topics of Kafka Connect.
This procedure outlines how access is granted using simple
authorization and ACLs.
Properties for the Kafka Connect cluster group ID and internal topics are configured by Strimzi by default.
Alternatively, you can define them explicitly in the spec
of the KafkaConnect
resource.
This is useful when configuring Kafka Connect for multiple instances, as the values for the group ID and topics must differ when running multiple Kafka Connect instances.
Simple authorization uses ACL rules managed by the Kafka AclAuthorizer
and StandardAuthorizer
plugins to ensure appropriate access levels.
For more information on configuring a KafkaUser
resource to use simple authorization, see the AclRule
schema reference.
Procedure
-
Edit the authorization
property in the KafkaUser
resource to provide access rights to the user.
Access rights are configured for the Kafka Connect topics and cluster group using literal
name values.
The following table shows the default names configured for the topics and cluster group ID.
Table 12. Names for the access rights configuration
Property |
Name |
offset.storage.topic
|
connect-cluster-offsets
|
status.storage.topic
|
connect-cluster-status
|
config.storage.topic
|
connect-cluster-configs
|
group
|
connect-cluster
|
In this example configuration, the default names are used to specify access rights.
If you are using different names for a Kafka Connect instance, use those names in the ACLs configuration.
Example configuration for simple authorization
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
# ...
authorization:
type: simple
acls:
# access to offset.storage.topic
- resource:
type: topic
name: connect-cluster-offsets
patternType: literal
operations:
- Create
- Describe
- Read
- Write
host: "*"
# access to status.storage.topic
- resource:
type: topic
name: connect-cluster-status
patternType: literal
operations:
- Create
- Describe
- Read
- Write
host: "*"
# access to config.storage.topic
- resource:
type: topic
name: connect-cluster-configs
patternType: literal
operations:
- Create
- Describe
- Read
- Write
host: "*"
# cluster group
- resource:
type: group
name: connect-cluster
patternType: literal
operations:
- Read
host: "*"
-
Create or update the resource.
kubectl apply -f KAFKA-USER-CONFIG-FILE
If you are using KafkaConnector
resources to configure connectors, use the state
configuration to either stop or pause a connector.
In contrast to the paused state, where the connector and tasks remain instantiated, stopping a connector retains only the configuration, with no active processes.
Stopping a connector from running may be more suitable for longer durations than just pausing.
While a paused connector is quicker to resume, a stopped connector has the advantages of freeing up memory and resources.
Note
|
The state configuration replaces the (deprecated) pause configuration in the KafkaConnectorSpec schema, which allows pauses on connectors.
If you were previously using the pause configuration to pause connectors, we encourage you to transition to using the state configuration only to avoid conflicts.
|
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the connector you want to pause or stop:
kubectl get KafkaConnector
-
Edit the KafkaConnector
resource to stop or pause the connector.
Example configuration for stopping a Kafka Connect connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: org.apache.kafka.connect.file.FileStreamSourceConnector
tasksMax: 2
config:
file: "/opt/kafka/LICENSE"
topic: my-topic
state: stopped
# ...
Change the state
configuration to stopped
or paused
.
The default state for the connector when this property is not set is running
.
-
Apply the changes to the KafkaConnector
configuration.
You can resume the connector by changing state
to running
or removing the configuration.
Note
|
Alternatively, you can expose the Kafka Connect API and use the stop and pause endpoints to stop a connector from running.
For example, PUT /connectors/<connector_name>/stop .
You can then use the resume endpoint to restart it.
|
If you are using KafkaConnector
resources to manage connectors, use the strimzi.io/restart
annotation to manually trigger a restart of a connector.
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the Kafka connector you want to restart:
kubectl get KafkaConnector
-
Restart the connector by annotating the KafkaConnector
resource in Kubernetes:
kubectl annotate KafkaConnector <kafka_connector_name> strimzi.io/restart="true"
The restart
annotation is set to true
.
-
Wait for the next reconciliation to occur (every two minutes by default).
The Kafka connector is restarted, as long as the annotation was detected by the reconciliation process.
When Kafka Connect accepts the restart request, the annotation is removed from the KafkaConnector
custom resource.
If you are using KafkaConnector
resources to manage connectors, use the strimzi.io/restart-task
annotation to manually trigger a restart of a connector task.
Procedure
-
Find the name of the KafkaConnector
custom resource that controls the Kafka connector task you want to restart:
kubectl get KafkaConnector
-
Find the ID of the task to be restarted from the KafkaConnector
custom resource:
kubectl describe KafkaConnector <kafka_connector_name>
Task IDs are non-negative integers, starting from 0.
-
Use the ID to restart the connector task by annotating the KafkaConnector
resource in Kubernetes:
kubectl annotate KafkaConnector <kafka_connector_name> strimzi.io/restart-task="0"
In this example, task 0
is restarted.
-
Wait for the next reconciliation to occur (every two minutes by default).
The Kafka connector task is restarted, as long as the annotation was detected by the reconciliation process.
When Kafka Connect accepts the restart request, the annotation is removed from the KafkaConnector
custom resource.
Update the spec
properties of the KafkaMirrorMaker2
custom resource to configure your MirrorMaker 2 deployment.
MirrorMaker 2 uses source cluster configuration for data consumption and target cluster configuration for data output.
MirrorMaker 2 is based on the Kafka Connect framework, connectors managing the transfer of data between clusters.
You configure MirrorMaker 2 to define the Kafka Connect deployment, including the connection details of the source and target clusters, and then run a set of MirrorMaker 2 connectors to make the connection.
MirrorMaker 2 supports topic configuration synchronization between the source and target clusters.
You specify source topics in the MirrorMaker 2 configuration.
MirrorMaker 2 monitors the source topics.
MirrorMaker 2 detects and propagates changes to the source topics to the remote topics.
Changes might include automatically creating missing topics and partitions.
Note
|
In most cases you write to local topics and read from remote topics. Though write operations are not prevented on remote topics, they should be avoided.
|
The configuration must specify:
Note
|
MirrorMaker 2 resource configuration differs from the previous version of MirrorMaker, which is now deprecated.
There is currently no legacy support, so any resources must be manually converted into the new format.
|
Default configuration
MirrorMaker 2 provides default configuration values for properties such as replication factors.
A minimal configuration, with defaults left unchanged, would be something like this example:
Minimal configuration for MirrorMaker 2
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
connectCluster: "my-cluster-target"
clusters:
- alias: "my-cluster-source"
bootstrapServers: my-cluster-source-kafka-bootstrap:9092
- alias: "my-cluster-target"
bootstrapServers: my-cluster-target-kafka-bootstrap:9092
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector: {}
You can configure access control for source and target clusters using mTLS or SASL authentication.
This procedure shows a configuration that uses TLS encryption and mTLS authentication for the source and target cluster.
You can specify the topics and consumer groups you wish to replicate from a source cluster in the KafkaMirrorMaker2
resource.
You use the topicsPattern
and groupsPattern
properties to do this.
You can provide a list of names or use a regular expression.
By default, all topics and consumer groups are replicated if you do not set the topicsPattern
and groupsPattern
properties.
You can also replicate all topics and consumer groups by using ".*"
as a regular expression.
However, try to specify only the topics and consumer groups you need to avoid causing any unnecessary extra load on the cluster.
Example KafkaMirrorMaker2
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2 # (1)
metadata:
name: my-mirror-maker2
# Deployment specifications
spec:
# Kafka version (recommended)
version: 3.8.0 # (1)
# Replicas (required)
replicas: 3 # (2)
# Connect cluster name (required)
connectCluster: "my-cluster-target" # (3)
# Cluster configurations (required)
clusters: # (4)
- alias: "my-cluster-source" # (5)
# Authentication (optional)
authentication: # (6)
certificateAndKey:
certificate: source.crt
key: source.key
secretName: my-user-source
type: tls
bootstrapServers: my-cluster-source-kafka-bootstrap:9092 # (7)
# TLS configuration (optional)
tls: # (8)
trustedCertificates:
- pattern: "*.crt"
secretName: my-cluster-source-cluster-ca-cert
- alias: "my-cluster-target" # (9)
# Authentication (optional)
authentication: # (10)
certificateAndKey:
certificate: target.crt
key: target.key
secretName: my-user-target
type: tls
bootstrapServers: my-cluster-target-kafka-bootstrap:9092 # (11)
# Kafka Connect configuration (optional)
config: # (12)
config.storage.replication.factor: 1
offset.storage.replication.factor: 1
status.storage.replication.factor: 1
# TLS configuration (optional)
tls: # (13)
trustedCertificates:
- pattern: "*.crt"
secretName: my-cluster-target-cluster-ca-cert
# Mirroring configurations (required)
mirrors: # (14)
- sourceCluster: "my-cluster-source" # (15)
targetCluster: "my-cluster-target" # (16)
# Source connector configuration (required)
sourceConnector: # (17)
tasksMax: 10 # (18)
autoRestart: # (19)
enabled: true
config:
replication.factor: 1 # (20)
offset-syncs.topic.replication.factor: 1 # (21)
sync.topic.acls.enabled: "false" # (22)
refresh.topics.interval.seconds: 60 # (23)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy" # (24)
# Heartbeat connector configuration (optional)
heartbeatConnector: # (25)
autoRestart:
enabled: true
config:
heartbeats.topic.replication.factor: 1 # (26)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"
# Checkpoint connector configuration (optional)
checkpointConnector: # (27)
autoRestart:
enabled: true
config:
checkpoints.topic.replication.factor: 1 # (28)
refresh.groups.interval.seconds: 600 # (29)
sync.group.offsets.enabled: true # (30)
sync.group.offsets.interval.seconds: 60 # (31)
emit.checkpoints.interval.seconds: 60 # (32)
replication.policy.class: "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"
# Topic and group patterns (required)
topicsPattern: "topic1|topic2|topic3" # (33)
groupsPattern: "group1|group2|group3" # (34)
# Resources requests and limits (recommended)
resources: # (35)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# Logging configuration (optional)
logging: # (36)
type: inline
loggers:
connect.root.logger.level: INFO
# Readiness probe (optional)
readinessProbe: # (37)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# JVM options (optional)
jvmOptions: # (38)
"-Xmx": "1g"
"-Xms": "1g"
# Custom image (optional)
image: my-org/my-image:latest # (39)
# Rack awareness (optional)
rack:
topologyKey: topology.kubernetes.io/zone # (40)
# Pod template (optional)
template: # (41)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
connectContainer: # (42)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
# Tracing configuration (optional)
tracing:
type: opentelemetry # (43)
# External configuration (optional)
externalConfiguration: # (44)
env:
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: aws-creds
key: awsAccessKey
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-creds
key: awsSecretAccessKey
-
The Kafka Connect and MirrorMaker 2 version, which will always be the same.
-
The number of replica nodes for the workers that run tasks.
-
Kafka cluster alias for Kafka Connect, which must specify the target Kafka cluster. The Kafka cluster is used by Kafka Connect for its internal topics.
-
Specification for the Kafka clusters being synchronized.
-
Cluster alias for the source Kafka cluster.
-
Authentication for the source cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
-
Bootstrap server for connection to the source Kafka cluster.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Cluster alias for the target Kafka cluster.
-
Authentication for the target Kafka cluster is configured in the same way as for the source Kafka cluster.
-
Bootstrap server for connection to the target Kafka cluster.
-
Kafka Connect configuration.
Standard Apache Kafka configuration may be provided, restricted to those properties not managed directly by Strimzi.
-
TLS encryption for the target Kafka cluster is configured in the same way as for the source Kafka cluster.
-
MirrorMaker 2 connectors.
-
Cluster alias for the source cluster used by the MirrorMaker 2 connectors.
-
Cluster alias for the target cluster used by the MirrorMaker 2 connectors.
-
Configuration for the MirrorSourceConnector
that creates remote topics. The config
overrides the default configuration options.
-
The maximum number of tasks that the connector may create. Tasks handle the data replication and run in parallel. If the infrastructure supports the processing overhead, increasing this value can improve throughput. Kafka Connect distributes the tasks between members of the cluster. If there are more tasks than workers, workers are assigned multiple tasks. For sink connectors, aim to have one task for each topic partition consumed. For source connectors, the number of tasks that can run in parallel may also depend on the external system. The connector creates fewer than the maximum number of tasks if it cannot achieve the parallelism.
-
Enables automatic restarts of failed connectors and tasks. By default, the number of restarts is indefinite, but you can set a maximum on the number of automatic restarts using the maxRestarts
property.
-
Replication factor for mirrored topics created at the target cluster.
-
Replication factor for the MirrorSourceConnector
offset-syncs
internal topic that maps the offsets of the source and target clusters.
-
When ACL rules synchronization is enabled, ACLs are applied to synchronized topics. The default is true
. This feature is not compatible with the User Operator. If you are using the User Operator, set this property to false
.
-
Optional setting to change the frequency of checks for new topics. The default is for a check every 10 minutes.
-
Adds a policy that overrides the automatic renaming of remote topics. Instead of prepending the name with the name of the source cluster, the topic retains its original name. This optional setting is useful for active/passive backups and data migration. The property must be specified for all connectors. For bidirectional (active/active) replication, use the DefaultReplicationPolicy
class to automatically rename remote topics and specify the replication.policy.separator
property for all connectors to add a custom separator.
-
Configuration for the MirrorHeartbeatConnector
that performs connectivity checks. The config
overrides the default configuration options.
-
Replication factor for the heartbeat topic created at the target cluster.
-
Configuration for the MirrorCheckpointConnector
that tracks offsets. The config
overrides the default configuration options.
-
Replication factor for the checkpoints topic created at the target cluster.
-
Optional setting to change the frequency of checks for new consumer groups. The default is for a check every 10 minutes.
-
Optional setting to synchronize consumer group offsets, which is useful for recovery in an active/passive configuration. Synchronization is not enabled by default.
-
If the synchronization of consumer group offsets is enabled, you can adjust the frequency of the synchronization.
-
Adjusts the frequency of checks for offset tracking. If you change the frequency of offset synchronization, you might also need to adjust the frequency of these checks.
-
Topic replication from the source cluster defined as a comma-separated list or regular expression pattern. The source connector replicates the specified topics. The checkpoint connector tracks offsets for the specified topics. Here we request three topics by name.
-
Consumer group replication from the source cluster defined as a comma-separated list or regular expression pattern. The checkpoint connector replicates the specified consumer groups. Here we request three consumer groups by name.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified Kafka Connect loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Connect log4j.rootLogger
logger, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
SPECIALIZED OPTION: Rack awareness configuration for the deployment. This is a specialized option intended for a deployment within the same location, not across regions. Use this option if you want connectors to consume from the closest replica rather than the leader replica. In certain cases, consuming from the closest replica can improve network utilization or reduce costs . The topologyKey
must match a node label containing the rack ID. The example used in this configuration specifies a zone using the standard topology.kubernetes.io/zone
label. To consume from the closest replica, enable the RackAwareReplicaSelector
in the Kafka broker configuration.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
-
External configuration for a Kubernetes Secret mounted to Kafka MirrorMaker as an environment variable.
You can also use configuration provider plugins to load configuration values from external sources.
You can use MirrorMaker 2 in active/passive or active/active cluster configurations.
- active/active cluster configuration
-
An active/active configuration has two active clusters replicating data bidirectionally. Applications can use either cluster. Each cluster can provide the same data. In this way, you can make the same data available in different geographical locations. As consumer groups are active in both clusters, consumer offsets for replicated topics are not synchronized back to the source cluster.
- active/passive cluster configuration
-
An active/passive configuration has an active cluster replicating data to a passive cluster. The passive cluster remains on standby. You might use the passive cluster for data recovery in the event of system failure.
The expectation is that producers and consumers connect to active clusters only.
A MirrorMaker 2 cluster is required at each target destination.
The MirrorMaker 2 architecture supports bidirectional replication in an active/active cluster configuration.
Each cluster replicates the data of the other cluster using the concept of source and remote topics.
As the same topics are stored in each cluster, remote topics are automatically renamed by MirrorMaker 2 to represent the source cluster.
The name of the originating cluster is prepended to the name of the topic.
By flagging the originating cluster, topics are not replicated back to that cluster.
The concept of replication through remote topics is useful when configuring an architecture that requires data aggregation.
Consumers can subscribe to source and remote topics within the same cluster, without the need for a separate aggregation cluster.
The MirrorMaker 2 architecture supports unidirectional replication in an active/passive cluster configuration.
You can use an active/passive cluster configuration to make backups or migrate data to another cluster.
In this situation, you might not want automatic renaming of remote topics.
You can override automatic renaming by adding IdentityReplicationPolicy
to the source connector configuration.
With this configuration applied, topics retain their original names.
By default, Strimzi configures the group ID and names of the internal topics used by the Kafka Connect framework that MirrorMaker 2 runs on.
When running multiple instances of MirrorMaker 2, and they share the same connectCluster
value, you must change these default settings using the following config
properties:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
connectCluster: "my-cluster-target"
clusters:
- alias: "my-cluster-target"
config:
group.id: my-connect-cluster # (1)
offset.storage.topic: my-connect-cluster-offsets # (2)
config.storage.topic: my-connect-cluster-configs # (3)
status.storage.topic: my-connect-cluster-status # (4)
# ...
# ...
-
The Kafka Connect cluster group ID within Kafka.
-
Kafka topic that stores connector offsets.
-
Kafka topic that stores connector and task status configurations.
-
Kafka topic that stores connector and task status updates.
Note
|
Values for the three topics must be the same for all instances with the same group.id .
|
The connectCluster
setting specifies the alias of the target Kafka cluster used by Kafka Connect for its internal topics.
As a result, modifications to the connectCluster
, group ID, and internal topic naming configuration are specific to the target Kafka cluster.
You don’t need to make changes if two MirrorMaker 2 instances are using the same source Kafka cluster or in an active-active mode where each MirrorMaker 2 instance has a different connectCluster
setting and target cluster.
However, if multiple MirrorMaker 2 instances share the same connectCluster
, each instance connecting to the same target Kafka cluster is deployed with the same values.
In practice, this means all instances form a cluster and use the same internal topics.
Multiple instances attempting to use the same internal topics will cause unexpected errors, so you must change the values of these properties for each instance.
Use MirrorMaker 2 connector configuration for the internal connectors that orchestrate the synchronization of data between Kafka clusters.
MirrorMaker 2 consists of the following connectors:
MirrorSourceConnector
-
The source connector replicates topics from a source cluster to a target cluster. It also replicates ACLs and is necessary for the MirrorCheckpointConnector
to run.
MirrorCheckpointConnector
-
The checkpoint connector periodically tracks offsets. If enabled, it also synchronizes consumer group offsets between the source and target cluster.
MirrorHeartbeatConnector
-
The heartbeat connector periodically checks connectivity between the source and target cluster.
The following table describes connector properties and the connectors you configure to use them.
Table 13. MirrorMaker 2 connector configuration properties
Property |
sourceConnector |
checkpointConnector |
heartbeatConnector |
- admin.timeout.ms
-
Timeout for admin tasks, such as detecting new topics. Default is 60000 (1 minute).
|
✓ |
✓ |
✓ |
- replication.policy.class
-
Policy to define the remote topic naming convention. Default is org.apache.kafka.connect.mirror.DefaultReplicationPolicy .
|
✓ |
✓ |
✓ |
- replication.policy.separator
-
The separator used for topic naming in the target cluster. By default, the separator is set to a dot (.).
Separator configuration is only applicable to the DefaultReplicationPolicy replication policy class, which defines remote topic names.
The IdentityReplicationPolicy class does not use the property as topics retain their original names.
|
✓ |
✓ |
✓ |
- consumer.poll.timeout.ms
-
Timeout when polling the source cluster. Default is 1000 (1 second).
|
✓ |
✓ |
|
- offset-syncs.topic.location
-
The location of the offset-syncs topic, which can be the source (default) or target cluster.
|
✓ |
✓ |
|
- topic.filter.class
-
Topic filter to select the topics to replicate. Default is org.apache.kafka.connect.mirror.DefaultTopicFilter .
|
✓ |
✓ |
|
- config.property.filter.class
-
Topic filter to select the topic configuration properties to replicate. Default is org.apache.kafka.connect.mirror.DefaultConfigPropertyFilter .
|
✓ |
|
|
- config.properties.exclude
-
Topic configuration properties that should not be replicated. Supports comma-separated property names and regular expressions.
|
✓ |
|
|
- offset.lag.max
-
Maximum allowable (out-of-sync) offset lag before a remote partition is synchronized. Default is 100 .
|
✓ |
|
|
- offset-syncs.topic.replication.factor
-
Replication factor for the internal offset-syncs topic. Default is 3 .
|
✓ |
|
|
- refresh.topics.enabled
-
Enables check for new topics and partitions. Default is true .
|
✓ |
|
|
- refresh.topics.interval.seconds
-
Frequency of topic refresh. Default is 600 (10 minutes). By default, a check for new topics in the source cluster is made every 10 minutes.
You can change the frequency by adding refresh.topics.interval.seconds to the source connector configuration.
|
✓ |
|
|
- replication.factor
-
The replication factor for new topics. Default is 2 .
|
✓ |
|
|
|
✓ |
|
|
- sync.topic.acls.interval.seconds
-
Frequency of ACL synchronization. Default is 600 (10 minutes).
|
✓ |
|
|
- sync.topic.configs.enabled
-
Enables synchronization of topic configuration from the source cluster. Default is true .
|
✓ |
|
|
- sync.topic.configs.interval.seconds
-
Frequency of topic configuration synchronization. Default 600 (10 minutes).
|
✓ |
|
|
- checkpoints.topic.replication.factor
-
Replication factor for the internal checkpoints topic. Default is 3 .
|
|
✓ |
|
- emit.checkpoints.enabled
-
Enables synchronization of consumer offsets to the target cluster. Default is true .
|
|
✓ |
|
- emit.checkpoints.interval.seconds
-
Frequency of consumer offset synchronization. Default is 60 (1 minute).
|
|
✓ |
|
- group.filter.class
-
Group filter to select the consumer groups to replicate. Default is org.apache.kafka.connect.mirror.DefaultGroupFilter .
|
|
✓ |
|
- refresh.groups.enabled
-
Enables check for new consumer groups. Default is true .
|
|
✓ |
|
- refresh.groups.interval.seconds
-
Frequency of consumer group refresh. Default is 600 (10 minutes).
|
|
✓ |
|
- sync.group.offsets.enabled
-
Enables synchronization of consumer group offsets to the target cluster __consumer_offsets topic. Default is false .
|
|
✓ |
|
- sync.group.offsets.interval.seconds
-
Frequency of consumer group offset synchronization. Default is 60 (1 minute).
|
|
✓ |
|
- emit.heartbeats.enabled
-
Enables connectivity checks on the target cluster. Default is true .
|
|
|
✓ |
- emit.heartbeats.interval.seconds
-
Frequency of connectivity checks. Default is 1 (1 second).
|
|
|
✓ |
- heartbeats.topic.replication.factor
-
Replication factor for the internal heartbeats topic. Default is 3 .
|
|
|
✓ |
MirrorMaker 2 tracks offsets for consumer groups using internal topics.
offset-syncs
topic
-
The offset-syncs
topic maps the source and target offsets for replicated topic partitions from record metadata.
checkpoints
topic
-
The checkpoints
topic maps the last committed offset in the source and target cluster for replicated topic partitions in each consumer group.
As they are used internally by MirrorMaker 2, you do not interact directly with these topics.
MirrorCheckpointConnector
emits checkpoints for offset tracking.
Offsets for the checkpoints
topic are tracked at predetermined intervals through configuration.
Both topics enable replication to be fully restored from the correct offset position on failover.
The location of the offset-syncs
topic is the source
cluster by default.
You can use the offset-syncs.topic.location
connector configuration to change this to the target
cluster.
You need read/write access to the cluster that contains the topic.
Using the target cluster as the location of the offset-syncs
topic allows you to use MirrorMaker 2 even if you have only read access to the source cluster.
The __consumer_offsets
topic stores information on committed offsets for each consumer group.
Offset synchronization periodically transfers the consumer offsets for the consumer groups of a source cluster into the consumer offsets topic of a target cluster.
Offset synchronization is particularly useful in an active/passive configuration.
If the active cluster goes down, consumer applications can switch to the passive (standby) cluster and pick up from the last transferred offset position.
To use topic offset synchronization, enable the synchronization by adding sync.group.offsets.enabled
to the checkpoint connector configuration, and setting the property to true
.
Synchronization is disabled by default.
When using the IdentityReplicationPolicy
in the source connector, it also has to be configured in the checkpoint connector configuration.
This ensures that the mirrored consumer offsets will be applied for the correct topics.
Consumer offsets are only synchronized for consumer groups that are not active in the target cluster.
If the consumer groups are in the target cluster, the synchronization cannot be performed and an UNKNOWN_MEMBER_ID
error is returned.
If enabled, the synchronization of offsets from the source cluster is made periodically.
You can change the frequency by adding sync.group.offsets.interval.seconds
and emit.checkpoints.interval.seconds
to the checkpoint connector configuration.
The properties specify the frequency in seconds that the consumer group offsets are synchronized, and the frequency of checkpoints emitted for offset tracking.
The default for both properties is 60 seconds.
You can also change the frequency of checks for new consumer groups using the refresh.groups.interval.seconds
property, which is performed every 10 minutes by default.
Because the synchronization is time-based, any switchover by consumers to a passive cluster will likely result in some duplication of messages.
Note
|
If you have an application written in Java, you can use the RemoteClusterUtils.java utility to synchronize offsets through the application. The utility fetches remote offsets for a consumer group from the checkpoints topic.
|
The heartbeat connector emits heartbeats to check connectivity between source and target Kafka clusters.
An internal heartbeat
topic is replicated from the source cluster, which means that the heartbeat connector must be connected to the source cluster.
The heartbeat
topic is located on the target cluster, which allows it to do the following:
This helps to make sure that the process is not stuck or has stopped for any reason.
While the heartbeat connector can be a valuable tool for monitoring the mirroring processes between Kafka clusters, it’s not always necessary to use it.
For example, if your deployment has low network latency or a small number of topics, you might prefer to monitor the mirroring process using log messages or other monitoring tools.
If you decide not to use the heartbeat connector, simply omit it from your MirrorMaker 2 configuration.
To ensure that MirrorMaker 2 connectors work properly, make sure to align certain configuration settings across connectors.
Specifically, ensure that the following properties have the same value across all applicable connectors:
For example, the value for replication.policy.class
must be the same for the source, checkpoint, and heartbeat connectors.
Mismatched or missing settings cause issues with data replication or offset syncing, so it’s essential to keep all relevant connectors configured with the same settings.
MirrorMaker 2 connectors use internal producers and consumers.
If needed, you can configure these producers and consumers to override the default settings.
For example, you can increase the batch.size
for the source producer that sends topics to the target Kafka cluster to better accommodate large volumes of messages.
Important
|
Producer and consumer configuration options depend on the MirrorMaker 2 implementation, and may be subject to change.
|
The following tables describe the producers and consumers for each of the connectors and where you can add configuration.
Table 14. Source connector producers and consumers
Type |
Description |
Configuration |
Producer |
Sends topic messages to the target Kafka cluster. Consider tuning the configuration of this producer when it is handling large volumes of data.
|
mirrors.sourceConnector.config: producer.override.*
|
Producer |
Writes to the offset-syncs topic, which maps the source and target offsets for replicated topic partitions.
|
mirrors.sourceConnector.config: producer.*
|
Consumer |
Retrieves topic messages from the source Kafka cluster.
|
mirrors.sourceConnector.config: consumer.*
|
Table 15. Checkpoint connector producers and consumers
Type |
Description |
Configuration |
Producer |
Emits consumer offset checkpoints.
|
mirrors.checkpointConnector.config: producer.override.*
|
Consumer |
Loads the offset-syncs topic.
|
mirrors.checkpointConnector.config: consumer.*
|
Note
|
You can set offset-syncs.topic.location to target to use the target Kafka cluster as the location of the offset-syncs topic.
|
Table 16. Heartbeat connector producer
Type |
Description |
Configuration |
Producer |
|
mirrors.heartbeatConnector.config: producer.override.*
|
The following example shows how you configure the producers and consumers.
Example configuration for connector producers and consumers
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 5
config:
producer.override.batch.size: 327680
producer.override.linger.ms: 100
producer.request.timeout.ms: 30000
consumer.fetch.max.bytes: 52428800
# ...
checkpointConnector:
config:
producer.override.request.timeout.ms: 30000
consumer.max.poll.interval.ms: 300000
# ...
heartbeatConnector:
config:
producer.override.request.timeout.ms: 30000
# ...
Connectors create the tasks that are responsible for moving data in and out of Kafka.
Each connector comprises one or more tasks that are distributed across a group of worker pods that run the tasks.
Increasing the number of tasks can help with performance issues when replicating a large number of partitions or synchronizing the offsets of a large number of consumer groups.
Tasks run in parallel.
Workers are assigned one or more tasks.
A single task is handled by one worker pod, so you don’t need more worker pods than tasks.
If there are more tasks than workers, workers handle multiple tasks.
You can specify the maximum number of connector tasks in your MirrorMaker configuration using the tasksMax
property.
Without specifying a maximum number of tasks, the default setting is a single task.
The heartbeat connector always uses a single task.
The number of tasks that are started for the source and checkpoint connectors is the lower value between the maximum number of possible tasks and the value for tasksMax
.
For the source connector, the maximum number of tasks possible is one for each partition being replicated from the source cluster.
For the checkpoint connector, the maximum number of tasks possible is one for each consumer group being replicated from the source cluster.
When setting a maximum number of tasks, consider the number of partitions and the hardware resources that support the process.
If the infrastructure supports the processing overhead, increasing the number of tasks can improve throughput and latency.
For example, adding more tasks reduces the time taken to poll the source cluster when there is a high number of partitions or consumer groups.
Increasing the number of tasks for the source connector is useful when you have a large number of partitions.
Increasing the number of tasks for the source connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 10
# ...
Increasing the number of tasks for the checkpoint connector is useful when you have a large number of consumer groups.
Increasing the number of tasks for the checkpoint connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
checkpointConnector:
tasksMax: 10
# ...
By default, MirrorMaker 2 checks for new consumer groups every 10 minutes.
You can adjust the refresh.groups.interval.seconds
configuration to change the frequency.
Take care when adjusting lower.
More frequent checks can have a negative impact on performance.
If you are using Prometheus and Grafana to monitor your deployment, you can check MirrorMaker 2 performance.
The example MirrorMaker 2 Grafana dashboard provided with Strimzi shows the following metrics related to tasks and latency.
When using MirrorMaker 2 with Strimzi, it is possible to synchronize ACL rules for remote topics.
However, this feature is only available if you are not using the User Operator.
If you are using type: simple
authorization without the User Operator, the ACL rules that manage access to brokers also apply to remote topics.
This means that users who have read access to a source topic can also read its remote equivalent.
Note
|
OAuth 2.0 authorization does not support access to remote topics in this way.
|
This procedure describes in outline the configuration required to secure a MirrorMaker 2 deployment.
You need separate configuration for the source Kafka cluster and the target Kafka cluster.
You also need separate user configuration to provide the credentials required for MirrorMaker to connect to the source and target Kafka clusters.
For the Kafka clusters, you specify internal listeners for secure connections within a Kubernetes cluster and external listeners for connections outside the Kubernetes cluster.
You can configure authentication and authorization mechanisms.
The security options implemented for the source and target Kafka clusters must be compatible with the security options implemented for MirrorMaker 2.
After you have created the cluster and user authentication credentials, you specify them in your MirrorMaker configuration for secure connections.
Before you start
Before starting this procedure, take a look at the example configuration files provided by Strimzi.
They include examples for securing a deployment of MirrorMaker 2 using mTLS or SCRAM-SHA-512 authentication.
The examples specify internal listeners for connecting within a Kubernetes cluster.
The examples also provide the configuration for full authorization, including the ACLs that allow user operations on the source and target Kafka clusters.
When configuring user access to source and target Kafka clusters, ACLs must grant access rights to internal MirrorMaker 2 connectors and read/write access to the cluster group and internal topics used by the underlying Kafka Connect framework in the target cluster.
If you’ve renamed the cluster group or internal topics, such as when configuring MirrorMaker 2 for multiple instances, use those names in the ACLs configuration.
Simple authorization uses ACL rules managed by the Kafka AclAuthorizer
and StandardAuthorizer
plugins to ensure appropriate access levels.
For more information on configuring a KafkaUser
resource to use simple authorization, see the AclRule
schema reference.
The procedure assumes that the source and target Kafka clusters are installed to separate namespaces.
If you want to use the Topic Operator, you’ll need to do this.
The Topic Operator only watches a single cluster in a specified namespace.
By separating the clusters into namespaces, you will need to copy the cluster secrets so they can be accessed outside the namespace.
You need to reference the secrets in the MirrorMaker configuration.
Procedure
-
Configure two Kafka
resources, one to secure the source Kafka cluster and one to secure the target Kafka cluster.
You can add listener configuration for authentication and enable authorization.
In this example, an internal listener is configured for a Kafka cluster with TLS encryption and mTLS authentication.
Kafka simple
authorization is enabled.
Example source Kafka cluster configuration with TLS encryption and mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-source-cluster
spec:
kafka:
version: 3.8.0
replicas: 1
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
authorization:
type: simple
config:
offsets.topic.replication.factor: 1
transaction.state.log.replication.factor: 1
transaction.state.log.min.isr: 1
default.replication.factor: 1
min.insync.replicas: 1
inter.broker.protocol.version: "3.8"
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
zookeeper:
replicas: 1
storage:
type: persistent-claim
size: 100Gi
deleteClaim: false
entityOperator:
topicOperator: {}
userOperator: {}
Example target Kafka cluster configuration with TLS encryption and mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-target-cluster
spec:
kafka:
version: 3.8.0
replicas: 1
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
authorization:
type: simple
config:
offsets.topic.replication.factor: 1
transaction.state.log.replication.factor: 1
transaction.state.log.min.isr: 1
default.replication.factor: 1
min.insync.replicas: 1
inter.broker.protocol.version: "3.8"
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
zookeeper:
replicas: 1
storage:
type: persistent-claim
size: 100Gi
deleteClaim: false
entityOperator:
topicOperator: {}
userOperator: {}
-
Create or update the Kafka
resources in separate namespaces.
kubectl apply -f <kafka_configuration_file> -n <namespace>
The Cluster Operator creates the listeners and sets up the cluster and client certificate authority (CA) certificates to enable authentication within the Kafka cluster.
The certificates are created in the secret <cluster_name>-cluster-ca-cert
.
-
Configure two KafkaUser
resources, one for a user of the source Kafka cluster and one for a user of the target Kafka cluster.
-
Configure the same authentication and authorization types as the corresponding source and target Kafka cluster.
For example, if you used tls
authentication and the simple
authorization type in the Kafka
configuration for the source Kafka cluster, use the same in the KafkaUser
configuration.
-
Configure the ACLs needed by MirrorMaker 2 to allow operations on the source and target Kafka clusters.
Example source user configuration for mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-source-user
labels:
strimzi.io/cluster: my-source-cluster
spec:
authentication:
type: tls
authorization:
type: simple
acls:
# MirrorSourceConnector
- resource: # Not needed if offset-syncs.topic.location=target
type: topic
name: mm2-offset-syncs.my-target-cluster.internal
operations:
- Create
- DescribeConfigs
- Read
- Write
- resource: # Needed for every topic which is mirrored
type: topic
name: "*"
operations:
- DescribeConfigs
- Read
# MirrorCheckpointConnector
- resource:
type: cluster
operations:
- Describe
- resource: # Needed for every group for which offsets are synced
type: group
name: "*"
operations:
- Describe
- resource: # Not needed if offset-syncs.topic.location=target
type: topic
name: mm2-offset-syncs.my-target-cluster.internal
operations:
- Read
Example target user configuration for mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-target-user
labels:
strimzi.io/cluster: my-target-cluster
spec:
authentication:
type: tls
authorization:
type: simple
acls:
# cluster group
- resource:
type: group
name: mirrormaker2-cluster
operations:
- Read
# access to config.storage.topic
- resource:
type: topic
name: mirrormaker2-cluster-configs
operations:
- Create
- Describe
- DescribeConfigs
- Read
- Write
# access to status.storage.topic
- resource:
type: topic
name: mirrormaker2-cluster-status
operations:
- Create
- Describe
- DescribeConfigs
- Read
- Write
# access to offset.storage.topic
- resource:
type: topic
name: mirrormaker2-cluster-offsets
operations:
- Create
- Describe
- DescribeConfigs
- Read
- Write
# MirrorSourceConnector
- resource: # Needed for every topic which is mirrored
type: topic
name: "*"
operations:
- Create
- Alter
- AlterConfigs
- Write
# MirrorCheckpointConnector
- resource:
type: cluster
operations:
- Describe
- resource:
type: topic
name: my-source-cluster.checkpoints.internal
operations:
- Create
- Describe
- Read
- Write
- resource: # Needed for every group for which the offset is synced
type: group
name: "*"
operations:
- Read
- Describe
# MirrorHeartbeatConnector
- resource:
type: topic
name: heartbeats
operations:
- Create
- Describe
- Write
Note
|
You can use a certificate issued outside the User Operator by setting type to tls-external .
For more information, see the KafkaUserSpec schema reference.
|
-
Create or update a KafkaUser
resource in each of the namespaces you created for the source and target Kafka clusters.
kubectl apply -f <kafka_user_configuration_file> -n <namespace>
The User Operator creates the users representing the client (MirrorMaker), and the security credentials used for client authentication, based on the chosen authentication type.
The User Operator creates a new secret with the same name as the KafkaUser
resource.
The secret contains a private and public key for mTLS authentication.
The public key is contained in a user certificate, which is signed by the clients CA.
-
Configure a KafkaMirrorMaker2
resource with the authentication details to connect to the source and target Kafka clusters.
Example MirrorMaker 2 configuration with TLS encryption and mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker-2
spec:
version: 3.8.0
replicas: 1
connectCluster: "my-target-cluster"
clusters:
- alias: "my-source-cluster"
bootstrapServers: my-source-cluster-kafka-bootstrap:9093
tls: # (1)
trustedCertificates:
- secretName: my-source-cluster-cluster-ca-cert
pattern: "*.crt"
authentication: # (2)
type: tls
certificateAndKey:
secretName: my-source-user
certificate: user.crt
key: user.key
- alias: "my-target-cluster"
bootstrapServers: my-target-cluster-kafka-bootstrap:9093
tls: # (3)
trustedCertificates:
- secretName: my-target-cluster-cluster-ca-cert
pattern: "*.crt"
authentication: # (4)
type: tls
certificateAndKey:
secretName: my-target-user
certificate: user.crt
key: user.key
config:
# -1 means it will use the default replication factor configured in the broker
config.storage.replication.factor: -1
offset.storage.replication.factor: -1
status.storage.replication.factor: -1
mirrors:
- sourceCluster: "my-source-cluster"
targetCluster: "my-target-cluster"
sourceConnector:
config:
replication.factor: 1
offset-syncs.topic.replication.factor: 1
sync.topic.acls.enabled: "false"
heartbeatConnector:
config:
heartbeats.topic.replication.factor: 1
checkpointConnector:
config:
checkpoints.topic.replication.factor: 1
sync.group.offsets.enabled: "true"
topicsPattern: "topic1|topic2|topic3"
groupsPattern: "group1|group2|group3"
-
The TLS certificates for the source Kafka cluster. If they are in a separate namespace, copy the cluster secrets from the namespace of the Kafka cluster.
-
The user authentication for accessing the source Kafka cluster using the TLS mechanism.
-
The TLS certificates for the target Kafka cluster.
-
The user authentication for accessing the target Kafka cluster.
-
Create or update the KafkaMirrorMaker2
resource in the same namespace as the target Kafka cluster.
kubectl apply -f <mirrormaker2_configuration_file> -n <namespace_of_target_cluster>
If you are using KafkaMirrorMaker2
resources to configure internal MirrorMaker connectors, use the state
configuration to either stop or pause a connector.
In contrast to the paused state, where the connector and tasks remain instantiated, stopping a connector retains only the configuration, with no active processes.
Stopping a connector from running may be more suitable for longer durations than just pausing.
While a paused connector is quicker to resume, a stopped connector has the advantages of freeing up memory and resources.
Note
|
The state configuration replaces the (deprecated) pause configuration in the KafkaMirrorMaker2ConnectorSpec schema, which allows pauses on connectors.
If you were previously using the pause configuration to pause connectors, we encourage you to transition to using the state configuration only to avoid conflicts.
|
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the MirrorMaker 2 connector you want to pause or stop:
kubectl get KafkaMirrorMaker2
-
Edit the KafkaMirrorMaker2
resource to stop or pause the connector.
Example configuration for stopping a MirrorMaker 2 connector
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
replicas: 3
connectCluster: "my-cluster-target"
clusters:
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 10
autoRestart:
enabled: true
state: stopped
# ...
Change the state
configuration to stopped
or paused
.
The default state for the connector when this property is not set is running
.
-
Apply the changes to the KafkaMirrorMaker2
configuration.
You can resume the connector by changing state
to running
or removing the configuration.
Note
|
Alternatively, you can expose the Kafka Connect API and use the stop and pause endpoints to stop a connector from running.
For example, PUT /connectors/<connector_name>/stop .
You can then use the resume endpoint to restart it.
|
Use the strimzi.io/restart-connector
annotation to manually trigger a restart of a MirrorMaker 2 connector.
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the Kafka MirrorMaker 2 connector you want to restart:
kubectl get KafkaMirrorMaker2
-
Find the name of the Kafka MirrorMaker 2 connector to be restarted from the KafkaMirrorMaker2
custom resource:
kubectl describe KafkaMirrorMaker2 <mirrormaker_cluster_name>
-
Use the name of the connector to restart the connector by annotating the KafkaMirrorMaker2
resource in Kubernetes:
kubectl annotate KafkaMirrorMaker2 <mirrormaker_cluster_name> "strimzi.io/restart-connector=<mirrormaker_connector_name>"
In this example, connector my-connector
in the my-mirror-maker-2
cluster is restarted:
kubectl annotate KafkaMirrorMaker2 my-mirror-maker-2 "strimzi.io/restart-connector=my-connector"
-
Wait for the next reconciliation to occur (every two minutes by default).
The MirrorMaker 2 connector is restarted, as long as the annotation was detected by the reconciliation process.
When MirrorMaker 2 accepts the request, the annotation is removed from the KafkaMirrorMaker2
custom resource.
Use the strimzi.io/restart-connector-task
annotation to manually trigger a restart of a MirrorMaker 2 connector.
Procedure
-
Find the name of the KafkaMirrorMaker2
custom resource that controls the MirrorMaker 2 connector task you want to restart:
kubectl get KafkaMirrorMaker2
-
Find the name of the connector and the ID of the task to be restarted from the KafkaMirrorMaker2
custom resource:
kubectl describe KafkaMirrorMaker2 <mirrormaker_cluster_name>
Task IDs are non-negative integers, starting from 0.
-
Use the name and ID to restart the connector task by annotating the KafkaMirrorMaker2
resource in Kubernetes:
kubectl annotate KafkaMirrorMaker2 <mirrormaker_cluster_name> "strimzi.io/restart-connector-task=<mirrormaker_connector_name>:<task_id>"
In this example, task 0
for connector my-connector
in the my-mirror-maker-2
cluster is restarted:
kubectl annotate KafkaMirrorMaker2 my-mirror-maker-2 "strimzi.io/restart-connector-task=my-connector:0"
-
Wait for the next reconciliation to occur (every two minutes by default).
The MirrorMaker 2 connector task is restarted, as long as the annotation was detected by the reconciliation process.
When MirrorMaker 2 accepts the request, the annotation is removed from the KafkaMirrorMaker2
custom resource.
Update the spec
properties of the KafkaMirrorMaker
custom resource to configure your Kafka MirrorMaker deployment.
You can configure access control for producers and consumers using TLS or SASL authentication.
This procedure shows a configuration that uses TLS encryption and mTLS authentication on the consumer and producer side.
Important
|
Kafka MirrorMaker 1 (referred to as just MirrorMaker in the documentation) has been deprecated in Apache Kafka 3.0.0 and will be removed in Apache Kafka 4.0.0.
As a result, the KafkaMirrorMaker custom resource which is used to deploy Kafka MirrorMaker 1 has been deprecated in Strimzi as well.
The KafkaMirrorMaker resource will be removed from Strimzi when we adopt Apache Kafka 4.0.0.
As a replacement, use the KafkaMirrorMaker2 custom resource with the IdentityReplicationPolicy .
|
Example KafkaMirrorMaker
custom resource configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker
metadata:
name: my-mirror-maker
spec:
replicas: 3 # (1)
consumer:
bootstrapServers: my-source-cluster-kafka-bootstrap:9092 # (2)
groupId: "my-group" # (3)
numStreams: 2 # (4)
offsetCommitInterval: 120000 # (5)
tls: # (6)
trustedCertificates:
- secretName: my-source-cluster-ca-cert
pattern: "*.crt"
authentication: # (7)
type: tls
certificateAndKey:
secretName: my-source-secret
certificate: public.crt
key: private.key
config: # (8)
max.poll.records: 100
receive.buffer.bytes: 32768
producer:
bootstrapServers: my-target-cluster-kafka-bootstrap:9092
abortOnSendFailure: false # (9)
tls:
trustedCertificates:
- secretName: my-target-cluster-ca-cert
pattern: "*.crt"
authentication:
type: tls
certificateAndKey:
secretName: my-target-secret
certificate: public.crt
key: private.key
config:
compression.type: gzip
batch.size: 8192
include: "my-topic|other-topic" # (10)
resources: # (11)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
logging: # (12)
type: inline
loggers:
mirrormaker.root.logger: INFO
readinessProbe: # (13)
initialDelaySeconds: 15
timeoutSeconds: 5
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
metricsConfig: # (14)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-key
jvmOptions: # (15)
"-Xmx": "1g"
"-Xms": "1g"
image: my-org/my-image:latest # (16)
template: # (17)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
mirrorMakerContainer: # (18)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing: # (19)
type: opentelemetry
-
The number of replica nodes.
-
Bootstrap servers for consumer and producer.
-
Group ID for the consumer.
-
The number of consumer streams.
-
The offset auto-commit interval in milliseconds.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Authentication for consumer or producer, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
-
Kafka configuration options for consumer and producer.
-
If the abortOnSendFailure
property is set to true
, Kafka MirrorMaker will exit and the container will restart following a send failure for a message.
-
A list of included topics mirrored from source to target Kafka cluster.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. MirrorMaker has a single logger called mirrormaker.root.logger
. You can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
Prometheus metrics, which are enabled by referencing a ConfigMap containing configuration for the Prometheus JMX exporter in this example. You can enable metrics without further configuration using a reference to a ConfigMap containing an empty file under metricsConfig.valueFrom.configMapKeyRef.key
.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running Kafka MirrorMaker.
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
Warning
|
With the abortOnSendFailure property set to false , the producer attempts to send the next message in a topic. The original message might be lost, as there is no attempt to resend a failed message.
|
Update the spec
properties of the KafkaBridge
custom resource to configure your Kafka Bridge deployment.
In order to prevent issues arising when client consumer requests are processed by different Kafka Bridge instances, address-based routing must be employed to ensure that requests are routed to the right Kafka Bridge instance.
Additionally, each independent Kafka Bridge instance must have a replica.
A Kafka Bridge instance has its own state which is not shared with another instances.
Example KafkaBridge
custom resource configuration
# Basic configuration (required)
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# Replicas (required)
replicas: 3 # (1)
# Kafka bootstrap servers (required)
bootstrapServers: <cluster_name>-cluster-kafka-bootstrap:9092 # (2)
# TLS configuration (optional)
tls: # (3)
trustedCertificates:
- secretName: my-cluster-cluster-cert
pattern: "*.crt"
- secretName: my-cluster-cluster-cert
certificate: ca2.crt
# Authentication (optional)
authentication: # (4)
type: tls
certificateAndKey:
secretName: my-secret
certificate: public.crt
key: private.key
# HTTP configuration (required)
http: # (5)
port: 8080
# CORS configuration (optional)
cors: # (6)
allowedOrigins: "https://strimzi.io"
allowedMethods: "GET,POST,PUT,DELETE,OPTIONS,PATCH"
# Consumer configuration (optional)
consumer: # (7)
config:
auto.offset.reset: earliest
# Producer configuration (optional)
producer: # (8)
config:
delivery.timeout.ms: 300000
# Resources requests and limits (recommended)
resources: # (9)
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# Logging configuration (optional)
logging: # (10)
type: inline
loggers:
logger.bridge.level: INFO
# Enabling DEBUG just for send operation
logger.send.name: "http.openapi.operation.send"
logger.send.level: DEBUG
# JVM options (optional)
jvmOptions: # (11)
"-Xmx": "1g"
"-Xms": "1g"
# Readiness probe (optional)
readinessProbe: # (12)
initialDelaySeconds: 15
timeoutSeconds: 5
# Liveness probe (optional)
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
# Custom image (optional)
image: my-org/my-image:latest # (13)
# Pod template (optional)
template: # (14)
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
bridgeContainer: # (15)
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
# Tracing configuration (optional)
tracing:
type: opentelemetry # (16)
-
The number of replica nodes.
-
Bootstrap server for connection to the target Kafka cluster. Use the name of the Kafka cluster as the <cluster_name>.
-
TLS configuration for encrypted connections to the Kafka cluster, with trusted certificates stored in X.509 format within the specified secrets.
-
Authentication for the Kafka Bridge cluster, specified as mTLS, token-based OAuth, SASL-based SCRAM-SHA-256/SCRAM-SHA-512, or PLAIN.
By default, the Kafka Bridge connects to Kafka brokers without authentication.
-
HTTP access to Kafka brokers.
-
CORS access specifying selected resources and access methods. Additional HTTP headers in requests describe the origins that are permitted access to the Kafka cluster.
-
Consumer configuration options.
-
Producer configuration options.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Specified Kafka Bridge loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
or log4j2.properties
key in the ConfigMap. For the Kafka Bridge loggers, you can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
JVM configuration options to optimize performance for the Virtual Machine (VM) running the Kafka Bridge.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
Optional: Container image configuration, which is recommended only in special situations.
-
Template customization. Here a pod is scheduled with anti-affinity, so the pod is not scheduled on nodes with the same hostname.
-
Environment variables are set for distributed tracing.
-
Distributed tracing is enabled by using OpenTelemetry.
Strimzi provides flexibility in configuring the data storage options of Kafka and ZooKeeper.
The supported storage types are:
-
Ephemeral (Recommended for development only)
-
Persistent
-
JBOD (Kafka only; not available for ZooKeeper)
-
Tiered storage (Early access)
To configure storage, you specify storage
properties in the custom resource of the component.
The storage type is set using the storage.type
property.
When using node pools, you can specify storage configuration unique to each node pool used in a Kafka cluster.
The same storage properties available to the Kafka
resource are also available to the KafkaNodePool
pool resource.
Tiered storage provides more flexibility for data management by leveraging the parallel use of storage types with different characteristics.
For example, tiered storage might include the following:
Tiered storage is an early access feature in Kafka.
To configure tiered storage, you specify tieredStorage
properties.
Tiered storage is configured only at the cluster level using the Kafka
custom resource.
The storage-related schema references provide more information on the storage configuration properties:
Warning
|
The storage type cannot be changed after a Kafka cluster is deployed.
|
For Strimzi to work well, an efficient data storage infrastructure is essential.
We strongly recommend using block storage.
Strimzi is only tested for use with block storage.
File storage, such as NFS, is not tested and there is no guarantee it will work.
Choose one of the following options for your block storage:
Note
|
Strimzi does not require Kubernetes raw block volumes.
|
Kafka uses a file system for storing messages.
Strimzi is compatible with the XFS and ext4 file systems, which are commonly used with Kafka.
Consider the underlying architecture and requirements of your deployment when choosing and setting up your file system.
Use separate disks for Apache Kafka and ZooKeeper.
Solid-state drives (SSDs), though not essential, can improve the performance of Kafka in large clusters where data is sent to and received from multiple topics asynchronously.
SSDs are particularly effective with ZooKeeper, which requires fast, low latency data access.
Note
|
You do not need to provision replicated storage because Kafka and ZooKeeper both have built-in data replication.
|
Ephemeral data storage is transient.
All pods on a node share a local ephemeral storage space.
Data is retained for as long as the pod that uses it is running.
The data is lost when a pod is deleted.
Although a pod can recover data in a highly available environment.
Because of its transient nature, ephemeral storage is only recommended for development and testing.
Ephemeral storage uses emptyDir
volumes to store data.
An emptyDir
volume is created when a pod is assigned to a node.
You can set the total amount of storage for the emptyDir
using the sizeLimit
property .
Important
|
Ephemeral storage is not suitable for single-node ZooKeeper clusters or Kafka topics with a replication factor of 1.
|
To use ephemeral storage, you set the storage type configuration in the Kafka
or ZooKeeper
resource to ephemeral
.
If you are using node pools, you can also specify ephemeral
in the storage configuration of individual node pools.
Example ephemeral storage configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
storage:
type: ephemeral
# ...
zookeeper:
storage:
type: ephemeral
# ...
The ephemeral volume is used by Kafka brokers as log directories mounted into the following path:
/var/lib/kafka/data/kafka-logIDX
Where IDX
is the Kafka broker pod index. For example /var/lib/kafka/data/kafka-log0
.
Persistent data storage retains data in the event of system disruption.
For pods that use persistent data storage, data is persisted across pod failures and restarts.
Because of its permanent nature, persistent storage is recommended for production environments.
The following examples show common types of persistent volumes supported by Kubernetes:
-
If your Kubernetes cluster runs on Amazon AWS, Kubernetes can provision Amazon EBS volumes
-
If your Kubernetes cluster runs on Microsoft Azure, Kubernetes can provision Azure Disk Storage volumes
-
If your Kubernetes cluster runs on Google Cloud, Kubernetes can provision Persistent Disk volumes
-
If your Kubernetes cluster runs on bare metal, Kubernetes can provision local persistent volumes
To use persistent storage in Strimzi, you specify persistent-claim
in the storage configuration of the Kafka
or ZooKeeper
resources.
If you are using node pools, you can also specify persistent-claim
in the storage configuration of individual node pools.
You configure the resource so that pods use Persistent Volume Claims (PVCs) to make storage requests on persistent volumes (PVs).
PVs represent storage volumes that are created on demand and are independent of the pods that use them.
The PVC requests the amount of storage required when a pod is being created.
The underlying storage infrastructure of the PV does not need to be understood.
If a PV matches the storage criteria, the PVC is bound to the PV.
You have two options for specifying the storage type:
storage.type: persistent-claim
-
If you choose persistent-claim
as the storage type, a single persistent storage volume is defined.
storage.type: jbod
-
When you select jbod
as the storage type, you have the flexibility to define an array of persistent storage volumes using unique IDs.
In a production environment, it is recommended to configure the following:
-
For Kafka or node pools, set storage.type
to jbod
with one or more persistent volumes.
-
For ZooKeeper, set storage.type
as persistent-claim
for a single persistent volume.
Persistent storage also has the following configuration options:
id
(optional)
-
A storage identification number. This option is mandatory for storage volumes defined in a JBOD storage declaration.
Default is 0
.
size
(required)
-
The size of the persistent volume claim, for example, "1000Gi".
class
(optional)
-
PVCs can request different types of persistent storage by specifying a StorageClass.
Storage classes define storage profiles and dynamically provision PVs based on that profile.
If a storage class is not specified, the storage class marked as default in the Kubernetes cluster is used.
Persistent storage options might include SAN storage types or local persistent volumes.
selector
(optional)
-
Configuration to specify a specific PV.
Provides key:value pairs representing the labels of the volume selected.
deleteClaim
(optional)
-
Boolean value to specify whether the PVC is deleted when the cluster is uninstalled.
Default is false
.
Warning
|
Increasing the size of persistent volumes in an existing Strimzi cluster is only supported in Kubernetes versions that support persistent volume resizing. The persistent volume to be resized must use a storage class that supports volume expansion.
For other versions of Kubernetes and storage classes that do not support volume expansion, you must decide the necessary storage size before deploying the cluster.
Decreasing the size of existing persistent volumes is not possible.
|
Example persistent storage configuration for Kafka and ZooKeeper
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 1
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 2
type: persistent-claim
size: 100Gi
deleteClaim: false
# ...
zookeeper:
storage:
type: persistent-claim
size: 1000Gi
# ...
Example persistent storage configuration with specific storage class
# ...
storage:
type: persistent-claim
size: 500Gi
class: my-storage-class
# ...
Use a selector
to specify a labeled persistent volume that provides certain features, such as an SSD.
Example persistent storage configuration with selector
# ...
storage:
type: persistent-claim
size: 1Gi
selector:
hdd-type: ssd
deleteClaim: true
# ...
Warning
|
Storage class overrides are deprecated and will be removed in the future. As a replacement, use KafkaNodePool resources instead.
|
Instead of using the default storage class, you can specify a different storage class for one or more Kafka or ZooKeeper nodes.
This is useful, for example, when storage classes are restricted to different availability zones or data centers.
You can use the overrides
field for this purpose.
In this example, the default storage class is named my-storage-class
:
Example storage configuration with class overrides
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
# ...
kafka:
replicas: 3
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
class: my-storage-class
overrides:
- broker: 0
class: my-storage-class-zone-1a
- broker: 1
class: my-storage-class-zone-1b
- broker: 2
class: my-storage-class-zone-1c
# ...
# ...
zookeeper:
replicas: 3
storage:
deleteClaim: true
size: 100Gi
type: persistent-claim
class: my-storage-class
overrides:
- broker: 0
class: my-storage-class-zone-1a
- broker: 1
class: my-storage-class-zone-1b
- broker: 2
class: my-storage-class-zone-1c
# ...
As a result of the configured overrides
property, the volumes use the following storage classes:
-
The persistent volumes of ZooKeeper node 0 use my-storage-class-zone-1a
.
-
The persistent volumes of ZooKeeper node 1 use my-storage-class-zone-1b
.
-
The persistent volumes of ZooKeeper node 2 use my-storage-class-zone-1c
.
-
The persistent volumes of Kafka broker 0 use my-storage-class-zone-1a
.
-
The persistent volumes of Kafka broker 1 use my-storage-class-zone-1b
.
-
The persistent volumes of Kafka broker 2 use my-storage-class-zone-1c
.
The overrides
property is currently used only to override the storage class
.
Overrides for other storage configuration properties is not currently supported.
Storage class overrides are deprecated and will be removed in the future.
If you are using storage class overrides, we encourage you to transition to using node pools instead.
To migrate the existing configuration, follow these steps:
When persistent storage is used, it creates PVCs with the following names:
data-cluster-name-kafka-idx
-
PVC for the volume used for storing data for the Kafka broker pod idx
.
data-cluster-name-zookeeper-idx
-
PVC for the volume used for storing data for the ZooKeeper node pod idx
.
The persistent volume is used by the Kafka brokers as log directories mounted into the following path:
/var/lib/kafka/data/kafka-logIDX
Where IDX
is the Kafka broker pod index. For example /var/lib/kafka/data/kafka-log0
.
Persistent volumes used by a cluster can be resized without any risk of data loss, as long as the storage infrastructure supports it.
Following a configuration update to change the size of the storage, Strimzi instructs the storage infrastructure to make the change.
Storage expansion is supported in Strimzi clusters that use persistent-claim volumes.
Storage reduction is only possible when using multiple disks per broker.
You can remove a disk after moving all partitions on the disk to other volumes within the same broker (intra-broker) or to other brokers within the same cluster (intra-cluster).
Important
|
You cannot decrease the size of persistent volumes because it is not currently supported in Kubernetes.
|
Prerequisites
-
A Kubernetes cluster with support for volume resizing.
-
The Cluster Operator is running.
-
A Kafka cluster using persistent volumes created using a storage class that supports volume expansion.
Procedure
-
Edit the Kafka
resource for your cluster.
Change the size
property to increase the size of the persistent volume allocated to a Kafka cluster, a ZooKeeper cluster, or both.
-
For Kafka clusters, update the size
property under spec.kafka.storage
.
-
For ZooKeeper clusters, update the size
property under spec.zookeeper.storage
.
Kafka configuration to increase the volume size to 2000Gi
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
storage:
type: persistent-claim
size: 2000Gi
class: my-storage-class
# ...
zookeeper:
# ...
-
Create or update the resource:
kubectl apply -f <kafka_configuration_file>
Kubernetes increases the capacity of the selected persistent volumes in response to a request from the Cluster Operator.
When the resizing is complete, the Cluster Operator restarts all pods that use the resized persistent volumes.
This happens automatically.
-
Verify that the storage capacity has increased for the relevant pods on the cluster:
Kafka broker pods with increased storage
NAME CAPACITY CLAIM
pvc-0ca459ce-... 2000Gi my-project/data-my-cluster-kafka-2
pvc-6e1810be-... 2000Gi my-project/data-my-cluster-kafka-0
pvc-82dc78c9-... 2000Gi my-project/data-my-cluster-kafka-1
The output shows the names of each PVC associated with a broker pod.
JBOD storage allows you to configure your Kafka cluster to use multiple disks or volumes.
This approach provides increased data storage capacity for Kafka nodes, and can lead to performance improvements.
A JBOD configuration is defined by one or more volumes, each of which can be either ephemeral or persistent.
The rules and constraints for JBOD volume declarations are the same as those for ephemeral and persistent storage.
For example, you cannot decrease the size of a persistent storage volume after it has been provisioned, nor can you change the value of sizeLimit
when the type is ephemeral
.
Note
|
JBOD storage is supported for Kafka only, not for ZooKeeper.
|
To use JBOD storage, you set the storage type configuration in the Kafka
resource to jbod
.
If you are using node pools, you can also specify jbod
in the storage configuration for nodes belonging to a specific node pool.
The volumes
property allows you to describe the disks that make up your JBOD storage array or configuration.
Example JBOD storage configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 1
type: persistent-claim
size: 100Gi
deleteClaim: false
# ...
The IDs cannot be changed once the JBOD volumes are created.
You can add or remove volumes from the JBOD configuration.
When persistent storage is used to declare JBOD volumes, it creates a PVC with the following name:
data-id-cluster-name-kafka-idx
-
PVC for the volume used for storing data for the Kafka broker pod idx
.
The id
is the ID of the volume used for storing data for Kafka broker pod.
The JBOD volumes are used by Kafka brokers as log directories mounted into the following path:
/var/lib/kafka/data-id/kafka-logidx
Where id
is the ID of the volume used for storing data for Kafka broker pod idx
. For example /var/lib/kafka/data-0/kafka-log0
.
In KRaft mode, a copy of the Kafka cluster’s metadata log is stored on every node, including brokers and controllers.
Each node uses one of its data volumes for the KRaft metadata log.
By default, the log is stored on the volume with the lowest ID.
However, you can specify another volume using the kraftMetadata
property.
For controller-only nodes, which don’t handle data, storage is used only used for the metadata log.
The metadata log is always stored only on one volume, so using JBOD storage with multiple volumes does not improve the performance or increase the available disk space.
Meanwhile, broker nodes or nodes combining broker and controller roles share the same volume for storing both the metadata log and partition replica data.
This sharing optimizes disk utilization.
They can also utilize JBOD storage with multiple volumes so that one of the volumes is shared by the metadata log and partition replica data and any additional volumes are used for partition replica data only.
Changing the volume that stores the metadata log triggers a rolling update of nodes in the cluster.
This process involves deleting the old metadata log and creating a new one in the new location.
If kraftMetadata
isn’t specified on any volume, adding a new volume with a lower ID also triggers an update and relocation of the metadata log.
Note
|
JBOD storage in KRaft mode is considered early-access in Apache Kafka 3.7.x.
|
Example JBOD storage configuration using volume with ID 1 to store the KRaft metadata
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaNodePool
metadata:
name: pool-a
# ...
spec:
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 1
type: persistent-claim
size: 100Gi
kraftMetadata: shared
deleteClaim: false
# ...
This procedure describes how to add volumes to a Kafka cluster configured to use JBOD storage.
It cannot be applied to Kafka clusters configured to use any other storage type.
Note
|
When adding a new volume under an id which was already used in the past and removed, you have to make sure that the previously used PersistentVolumeClaims have been deleted.
|
Procedure
-
Edit the spec.kafka.storage.volumes
property in the Kafka
resource.
Add the new volumes to the volumes
array.
For example, add the new volume with id 2
:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 1
type: persistent-claim
size: 100Gi
deleteClaim: false
- id: 2
type: persistent-claim
size: 100Gi
deleteClaim: false
# ...
zookeeper:
# ...
-
Create or update the resource:
kubectl apply -f <kafka_configuration_file>
-
Create new topics or reassign existing partitions to the new disks.
Tip
|
Cruise Control is an effective tool for reassigning partitions.
To perform an intra-broker disk balance, you set rebalanceDisk to true under the KafkaRebalance.spec .
|
This procedure describes how to remove volumes from a Kafka cluster configured to use JBOD storage.
It cannot be applied to Kafka clusters configured to use any other storage type.
The JBOD storage always has to contain at least one volume.
Important
|
To avoid data loss, you have to move all partitions before removing the volumes.
|
Procedure
-
Reassign all partitions from the disks which are you going to remove.
Any data in partitions still assigned to the disks which are going to be removed might be lost.
Tip
|
You can use the kafka-reassign-partitions.sh tool to reassign the partitions.
|
-
Edit the spec.kafka.storage.volumes
property in the Kafka
resource.
Remove one or more volumes from the volumes
array.
For example, remove the volumes with ids 1
and 2
:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 100Gi
deleteClaim: false
# ...
zookeeper:
# ...
-
Create or update the resource:
kubectl apply -f <kafka_configuration_file>
Tiered storage introduces a flexible approach to managing Kafka data whereby log segments are moved to a separate storage system.
For example, you can combine the use of block storage on brokers for frequently accessed data and offload older or less frequently accessed data from the block storage to more cost-effective, scalable remote storage solutions, such as Amazon S3, without compromising data accessibility and durability.
Warning
|
Tiered storage is an early access Kafka feature, which is also available in Strimzi.
Due to its current limitations, it is not recommended for production environments.
|
Tiered storage requires an implementation of Kafka’s RemoteStorageManager
interface to handle communication between Kafka and the remote storage system, which is enabled through configuration of the Kafka
resource.
Strimzi uses Kafka’s TopicBasedRemoteLogMetadataManager
for Remote Log Metadata Management (RLMM) when custom tiered storage is enabled.
The RLMM manages the metadata related to remote storage.
To use custom tiered storage, do the following:
-
Include a tiered storage plugin for Kafka in the Strimzi image by building a custom container image.
The plugin must provide the necessary functionality for a Kafka cluster managed by Strimzi to interact with the tiered storage solution.
-
Configure Kafka for tiered storage using tieredStorage
properties in the Kafka
resource.
Specify the class name and path for the custom RemoteStorageManager
implementation, as well as any additional configuration.
-
If required, specify RLMM-specific tiered storage configuration.
Example custom tiered storage configuration for Kafka
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
tieredStorage:
type: custom # (1)
remoteStorageManager: # (2)
className: com.example.kafka.tiered.storage.s3.S3RemoteStorageManager
classPath: /opt/kafka/plugins/tiered-storage-s3/*
config:
storage.bucket.name: my-bucket # (3)
# ...
config:
rlmm.config.remote.log.metadata.topic.replication.factor: 1 # (4)
# ...
-
The type
must be set to custom
.
-
The configuration for the custom RemoteStorageManager
implementation, including class name and path.
-
Configuration to pass to the custom RemoteStorageManager
implementation, which Strimzi automatically prefixes with rsm.config.
.
-
Tiered storage configuration to pass to the RLMM, which requires an rlmm.config.
prefix. For more information on tiered storage configuration, see the Apache Kafka documentation.
By default, the Strimzi Cluster Operator does not specify CPU and memory resource requests and limits for its deployed operands.
Ensuring an adequate allocation of resources is crucial for maintaining stability and achieving optimal performance in Kafka.
The ideal resource allocation depends on your specific requirements and use cases.
Kubernetes labels make it easier to organize, manage, and discover Kubernetes resources within your applications.
The Cluster Operator is responsible for applying the following Kubernetes labels to the operands it deploys.
These labels cannot be overridden through template
configuration of Strimzi resources:
-
app.kubernetes.io/name
: Identifies the component type within Strimzi, such as kafka
, zookeeper
, and`cruise-control`.
-
app.kubernetes.io/instance
: Represents the name of the custom resource to which the operand belongs to. For instance, if a Kafka custom resource is named my-cluster
, this label will bear that name on the associated pods.
-
app.kubernetes.io/part-of
: Similar to app.kubernetes.io/instance
, but prefixed with strimzi-
.
-
app.kubernetes.io/managed-by
: Defines the application responsible for managing the operand, such as strimzi-cluster-operator
or strimzi-user-operator
.
Example Kubernetes labels on a Kafka pod when deploying a Kafka
custom resource named my-cluster
apiVersion: kafka.strimzi.io/v1beta2
kind: Pod
metadata:
name: my-cluster-kafka-0
labels:
app.kubernetes.io/instance: my-cluster
app.kubernetes.io/managed-by: strimzi-cluster-operator
app.kubernetes.io/name: kafka
app.kubernetes.io/part-of: strimzi-my-cluster
spec:
# ...
To avoid performance degradation caused by resource conflicts between applications scheduled on the same Kubernetes node, you can schedule Kafka pods separately from critical workloads.
This can be achieved by either selecting specific nodes or dedicating a set of nodes exclusively for Kafka.
Use affinity, tolerations and topology spread constraints to schedule the pods of kafka resources onto nodes.
Affinity, tolerations and topology spread constraints are configured using the affinity
, tolerations
, and topologySpreadConstraint
properties in following resources:
-
Kafka.spec.kafka.template.pod
-
Kafka.spec.zookeeper.template.pod
-
Kafka.spec.entityOperator.template.pod
-
KafkaConnect.spec.template.pod
-
KafkaBridge.spec.template.pod
-
KafkaMirrorMaker.spec.template.pod
-
KafkaMirrorMaker2.spec.template.pod
The format of the affinity
, tolerations
, and topologySpreadConstraint
properties follows the Kubernetes specification.
The affinity configuration can include different types of affinity:
Use pod anti-affinity to ensure that critical applications are never scheduled on the same disk.
When running a Kafka cluster, it is recommended to use pod anti-affinity to ensure that the Kafka brokers do not share nodes with other workloads, such as databases.
The Kubernetes cluster usually consists of many different types of worker nodes.
Some are optimized for CPU heavy workloads, some for memory, while other might be optimized for storage (fast local SSDs) or network.
Using different nodes helps to optimize both costs and performance.
To achieve the best possible performance, it is important to allow scheduling of Strimzi components to use the right nodes.
Kubernetes uses node affinity to schedule workloads onto specific nodes.
Node affinity allows you to create a scheduling constraint for the node on which the pod will be scheduled.
The constraint is specified as a label selector.
You can specify the label using either the built-in node label like beta.kubernetes.io/instance-type
or custom labels to select the right node.
Use taints to create dedicated nodes, then schedule Kafka pods on the dedicated nodes by configuring node affinity and tolerations.
Cluster administrators can mark selected Kubernetes nodes as tainted.
Nodes with taints are excluded from regular scheduling and normal pods will not be scheduled to run on them.
Only services which can tolerate the taint set on the node can be scheduled on it.
The only other services running on such nodes will be system services such as log collectors or software defined networks.
Running Kafka and its components on dedicated nodes can have many advantages.
There will be no other applications running on the same nodes which could cause disturbance or consume the resources needed for Kafka.
That can lead to improved performance and stability.
Many Kafka brokers or ZooKeeper nodes can run on the same Kubernetes worker node.
If the worker node fails, they will all become unavailable at the same time.
To improve reliability, you can use podAntiAffinity
configuration to schedule each Kafka broker or ZooKeeper node on a different Kubernetes worker node.
Procedure
-
Edit the affinity
property in the resource specifying the cluster deployment.
To make sure that no worker nodes are shared by Kafka brokers or ZooKeeper nodes, use the strimzi.io/name
label.
Set the topologyKey
to kubernetes.io/hostname
to specify that the selected pods are not scheduled on nodes with the same hostname.
This will still allow the same worker node to be shared by a single Kafka broker and a single ZooKeeper node.
For example:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
template:
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: strimzi.io/name
operator: In
values:
- CLUSTER-NAME-kafka
topologyKey: "kubernetes.io/hostname"
# ...
zookeeper:
# ...
template:
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: strimzi.io/name
operator: In
values:
- CLUSTER-NAME-zookeeper
topologyKey: "kubernetes.io/hostname"
# ...
Where CLUSTER-NAME
is the name of your Kafka custom resource.
-
If you even want to make sure that a Kafka broker and ZooKeeper node do not share the same worker node, use the strimzi.io/cluster
label.
For example:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
template:
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: strimzi.io/cluster
operator: In
values:
- CLUSTER-NAME
topologyKey: "kubernetes.io/hostname"
# ...
zookeeper:
# ...
template:
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: strimzi.io/cluster
operator: In
values:
- CLUSTER-NAME
topologyKey: "kubernetes.io/hostname"
# ...
Where CLUSTER-NAME
is the name of your Kafka custom resource.
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
Pod anti-affinity configuration helps with the stability and performance of Kafka brokers. By using podAntiAffinity
, Kubernetes will not schedule Kafka brokers on the same nodes as other workloads.
Typically, you want to avoid Kafka running on the same worker node as other network or storage intensive applications such as databases, storage or other messaging platforms.
Procedure
-
Edit the affinity
property in the resource specifying the cluster deployment.
Use labels to specify the pods which should not be scheduled on the same nodes.
The topologyKey
should be set to kubernetes.io/hostname
to specify that the selected pods should not be scheduled on nodes with the same hostname.
For example:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
template:
pod:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: application
operator: In
values:
- postgresql
- mongodb
topologyKey: "kubernetes.io/hostname"
# ...
zookeeper:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
Procedure
-
Label the nodes where Strimzi components should be scheduled.
This can be done using kubectl label
:
kubectl label node NAME-OF-NODE node-type=fast-network
Alternatively, some of the existing labels might be reused.
-
Edit the affinity
property in the resource specifying the cluster deployment.
For example:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
template:
pod:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: node-type
operator: In
values:
- fast-network
# ...
zookeeper:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
Procedure
-
Select the nodes which should be used as dedicated.
-
Make sure there are no workloads scheduled on these nodes.
-
Set the taints on the selected nodes:
This can be done using kubectl taint
:
kubectl taint node NAME-OF-NODE dedicated=Kafka:NoSchedule
-
Additionally, add a label to the selected nodes as well.
This can be done using kubectl label
:
kubectl label node NAME-OF-NODE dedicated=Kafka
-
Edit the affinity
and tolerations
properties in the resource specifying the cluster deployment.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
template:
pod:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "Kafka"
effect: "NoSchedule"
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: dedicated
operator: In
values:
- Kafka
# ...
zookeeper:
# ...
-
Create or update the resource.
This can be done using kubectl apply
:
kubectl apply -f <kafka_configuration_file>
Configure logging levels in the custom resources of Kafka components and Strimzi operators.
You can specify the logging levels directly in the spec.logging
property of the custom resource.
Or you can define the logging properties in a ConfigMap that’s referenced in the custom resource using the configMapKeyRef
property.
The advantages of using a ConfigMap are that the logging properties are maintained in one place and are accessible to more than one resource.
You can also reuse the ConfigMap for more than one resource.
If you are using a ConfigMap to specify loggers for Strimzi Operators, you can also append the logging specification to add filters.
You specify a logging type
in your logging specification:
Example inline
logging configuration
# ...
logging:
type: inline
loggers:
kafka.root.logger.level: INFO
# ...
Example external
logging configuration
# ...
logging:
type: external
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-config-map-key
# ...
Values for the name
and key
of the ConfigMap are mandatory.
Default logging is used if the name
or key
is not set.
For more information on configuring logging for specific Kafka components or operators, see the following sections.
To use a ConfigMap to define logging properties, you create the ConfigMap and then reference it as part of the logging definition in the spec
of a resource.
The ConfigMap must contain the appropriate logging configuration.
-
log4j.properties
for Kafka components, ZooKeeper, and the Kafka Bridge
-
log4j2.properties
for the Topic Operator and User Operator
The configuration must be placed under these properties.
In this procedure a ConfigMap defines a root logger for a Kafka resource.
Procedure
-
Create the ConfigMap.
You can create the ConfigMap as a YAML file or from a properties file.
ConfigMap example with a root logger definition for Kafka:
kind: ConfigMap
apiVersion: v1
metadata:
name: logging-configmap
data:
log4j.properties:
kafka.root.logger.level="INFO"
If you are using a properties file, specify the file at the command line:
kubectl create configmap logging-configmap --from-file=log4j.properties
The properties file defines the logging configuration:
# Define the logger
kafka.root.logger.level="INFO"
# ...
-
Define external logging in the spec
of the resource, setting the logging.valueFrom.configMapKeyRef.name
to the name of the ConfigMap and logging.valueFrom.configMapKeyRef.key
to the key in this ConfigMap.
# ...
logging:
type: external
valueFrom:
configMapKeyRef:
name: logging-configmap
key: log4j.properties
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
Cluster Operator logging is configured through a ConfigMap
named strimzi-cluster-operator
.
A ConfigMap
containing logging configuration is created when installing the Cluster Operator.
This ConfigMap
is described in the file install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml
.
You configure Cluster Operator logging by changing the data.log4j2.properties
values in this ConfigMap
.
To update the logging configuration, you can edit the 050-ConfigMap-strimzi-cluster-operator.yaml
file and then run the following command:
kubectl create -f install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml
Alternatively, edit the ConfigMap
directly:
kubectl edit configmap strimzi-cluster-operator
With this ConfigMap, you can control various aspects of logging, including the root logger level, log output format, and log levels for different components.
The monitorInterval
setting, determines how often the logging configuration is reloaded.
You can also control the logging levels for the Kafka AdminClient
, ZooKeeper ZKTrustManager
, Netty, and the OkHttp client.
Netty is a framework used in Strimzi for network communication, and OkHttp is a library used for making HTTP requests.
If the ConfigMap
is missing when the Cluster Operator is deployed, the default logging values are used.
If the ConfigMap
is accidentally deleted after the Cluster Operator is deployed, the most recently loaded logging configuration is used.
Create a new ConfigMap
to load a new logging configuration.
Note
|
Do not remove the monitorInterval option from the ConfigMap .
|
If you are using a ConfigMap to configure the (log4j2) logging levels for Strimzi operators,
you can also define logging filters to limit what’s returned in the log.
Logging filters are useful when you have a large number of logging messages.
Suppose you set the log level for the logger as DEBUG (rootLogger.level="DEBUG"
).
Logging filters reduce the number of logs returned for the logger at that level, so you can focus on a specific resource.
When the filter is set, only log messages matching the filter are logged.
Filters use markers to specify what to include in the log.
You specify a kind, namespace and name for the marker.
For example, if a Kafka cluster is failing, you can isolate the logs by specifying the kind as Kafka
, and use the namespace and name of the failing cluster.
This example shows a marker filter for a Kafka cluster named my-kafka-cluster
.
Basic logging filter configuration
rootLogger.level="INFO"
appender.console.filter.filter1.type=MarkerFilter (1)
appender.console.filter.filter1.onMatch=ACCEPT (2)
appender.console.filter.filter1.onMismatch=DENY (3)
appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster) (4)
-
The MarkerFilter
type compares a specified marker for filtering.
-
The onMatch
property accepts the log if the marker matches.
-
The onMismatch
property rejects the log if the marker does not match.
-
The marker used for filtering is in the format KIND(NAMESPACE/NAME-OF-RESOURCE).
You can create one or more filters.
Here, the log is filtered for two Kafka clusters.
Multiple logging filter configuration
appender.console.filter.filter1.type=MarkerFilter
appender.console.filter.filter1.onMatch=ACCEPT
appender.console.filter.filter1.onMismatch=DENY
appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster-1)
appender.console.filter.filter2.type=MarkerFilter
appender.console.filter.filter2.onMatch=ACCEPT
appender.console.filter.filter2.onMismatch=DENY
appender.console.filter.filter2.marker=Kafka(my-namespace/my-kafka-cluster-2)
Adding filters to the Cluster Operator
To add filters to the Cluster Operator, update its logging ConfigMap YAML file (install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml
).
Procedure
-
Update the 050-ConfigMap-strimzi-cluster-operator.yaml
file to add the filter properties to the ConfigMap.
In this example, the filter properties return logs only for the my-kafka-cluster
Kafka cluster:
kind: ConfigMap
apiVersion: v1
metadata:
name: strimzi-cluster-operator
data:
log4j2.properties:
#...
appender.console.filter.filter1.type=MarkerFilter
appender.console.filter.filter1.onMatch=ACCEPT
appender.console.filter.filter1.onMismatch=DENY
appender.console.filter.filter1.marker=Kafka(my-namespace/my-kafka-cluster)
Alternatively, edit the ConfigMap
directly:
kubectl edit configmap strimzi-cluster-operator
-
If you updated the YAML file instead of editing the ConfigMap
directly, apply the changes by deploying the ConfigMap:
kubectl create -f install/cluster-operator/050-ConfigMap-strimzi-cluster-operator.yaml
Adding filters to the Topic Operator or User Operator
To add filters to the Topic Operator or User Operator, create or edit a logging ConfigMap.
In this procedure a logging ConfigMap is created with filters for the Topic Operator.
The same approach is used for the User Operator.
Procedure
-
Create the ConfigMap.
You can create the ConfigMap as a YAML file or from a properties file.
In this example, the filter properties return logs only for the my-topic
topic:
kind: ConfigMap
apiVersion: v1
metadata:
name: logging-configmap
data:
log4j2.properties:
rootLogger.level="INFO"
appender.console.filter.filter1.type=MarkerFilter
appender.console.filter.filter1.onMatch=ACCEPT
appender.console.filter.filter1.onMismatch=DENY
appender.console.filter.filter1.marker=KafkaTopic(my-namespace/my-topic)
If you are using a properties file, specify the file at the command line:
kubectl create configmap logging-configmap --from-file=log4j2.properties
The properties file defines the logging configuration:
# Define the logger
rootLogger.level="INFO"
# Set the filters
appender.console.filter.filter1.type=MarkerFilter
appender.console.filter.filter1.onMatch=ACCEPT
appender.console.filter.filter1.onMismatch=DENY
appender.console.filter.filter1.marker=KafkaTopic(my-namespace/my-topic)
# ...
-
Define external logging in the spec
of the resource, setting the logging.valueFrom.configMapKeyRef.name
to the name of the ConfigMap and logging.valueFrom.configMapKeyRef.key
to the key in this ConfigMap.
For the Topic Operator, logging is specified in the topicOperator
configuration of the Kafka
resource.
spec:
# ...
entityOperator:
topicOperator:
logging:
type: external
valueFrom:
configMapKeyRef:
name: logging-configmap
key: log4j2.properties
-
Apply the changes by deploying the Cluster Operator:
create -f install/cluster-operator -n my-cluster-operator-namespace
The Cluster Operator ensures that only one operation runs at a time for each cluster by using locks.
If another operation attempts to start while a lock is held, it waits until the current operation completes.
Operations such as cluster creation, rolling updates, scaling down, and scaling up are managed by the Cluster Operator.
If acquiring a lock takes longer than the configured timeout (STRIMZI_OPERATION_TIMEOUT_MS
), a DEBUG message is logged:
Example DEBUG message for lock acquisition
DEBUG AbstractOperator:406 - Reconciliation #55(timer) Kafka(myproject/my-cluster): Failed to acquire lock lock::myproject::Kafka::my-cluster within 10000ms.
Timed-out operations are retried during the next periodic reconciliation in intervals defined by STRIMZI_FULL_RECONCILIATION_INTERVAL_MS
(by default 120 seconds).
If an INFO message continues to appear with the same same reconciliation number, it might indicate a lock release error:
Example INFO message for reconciliation
INFO AbstractOperator:399 - Reconciliation #1(watch) Kafka(myproject/my-cluster): Reconciliation is in progress
Restarting the Cluster Operator can resolve such issues.
Add specific configuration to your Strimzi deployment using ConfigMap
resources.
ConfigMaps use key-value pairs to store non-confidential data.
Configuration data added to ConfigMaps is maintained in one place and can be reused amongst components.
ConfigMaps can only store the following types of configuration data:
You can’t use ConfigMaps for other areas of configuration.
When you configure a component, you can add a reference to a ConfigMap using the configMapKeyRef
property.
For example, you can use configMapKeyRef
to reference a ConfigMap that provides configuration for logging.
You might use a ConfigMap to pass a Log4j configuration file.
You add the reference to the logging
configuration.
Example ConfigMap for logging
# ...
logging:
type: external
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-config-map-key
# ...
To use a ConfigMap for metrics configuration, you add a reference to the metricsConfig
configuration of the component in the same way.
ExternalConfiguration
properties make data from a ConfigMap (or Secret) mounted to a pod available as environment variables or volumes.
You can use external configuration data for the connectors used by Kafka Connect.
The data might be related to an external data source, providing the values needed for the connector to communicate with that data source.
For example, you can use the configMapKeyRef
property to pass configuration data from a ConfigMap as an environment variable.
Example ConfigMap providing environment variable values
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
# ...
externalConfiguration:
env:
- name: MY_ENVIRONMENT_VARIABLE
valueFrom:
configMapKeyRef:
name: my-config-map
key: my-key
If you are using ConfigMaps that are managed externally, use configuration providers to load the data in the ConfigMaps.
Make sure that any custom ConfigMaps you create do not have the same name as these default ConfigMaps. If they have the same name, they will be overwritten. For example, if your ConfigMap has the same name as the ConfigMap for the Kafka cluster, it will be overwritten when there is an update to the Kafka cluster.
Use configuration providers to load configuration data from external sources.
The providers operate independently of Strimzi.
You can use them to load configuration data for all Kafka components, including producers and consumers.
You reference the external source in the configuration of the component and provide access rights.
The provider loads data without needing to restart the Kafka component or extracting files, even when referencing a new external source.
For example, use providers to supply the credentials for the Kafka Connect connector configuration.
The configuration must include any access rights to the external source.
You can enable one or more configuration providers using the config.providers
properties in the spec
configuration of a component.
Example configuration to enable a configuration provider
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
annotations:
strimzi.io/use-connector-resources: "true"
spec:
# ...
config:
# ...
config.providers: env
config.providers.env.class: org.apache.kafka.common.config.provider.EnvVarConfigProvider
# ...
- KubernetesSecretConfigProvider
-
Loads configuration data from Kubernetes secrets.
You specify the name of the secret and the key within the secret where the configuration data is stored.
This provider is useful for storing sensitive configuration data like passwords or other user credentials.
- KubernetesConfigMapConfigProvider
-
Loads configuration data from Kubernetes config maps.
You specify the name of the config map and the key within the config map where the configuration data is stored.
This provider is useful for storing non-sensitive configuration data.
- EnvVarConfigProvider
-
Loads configuration data from environment variables.
You specify the name of the environment variable where the configuration data is stored.
This provider is useful for configuring applications running in containers, for example, to load certificates or JAAS configuration from environment variables mapped from secrets.
- FileConfigProvider
-
Loads configuration data from a file.
You specify the path to the file where the configuration data is stored.
This provider is useful for loading configuration data from files that are mounted into containers.
- DirectoryConfigProvider
-
Loads configuration data from files within a directory.
You specify the path to the directory where the configuration files are stored.
This provider is useful for loading multiple configuration files and for organizing configuration data into separate files.
To use KubernetesSecretConfigProvider
and KubernetesConfigMapConfigProvider
, which are part of the Kubernetes Configuration Provider plugin, you must set up access rights to the namespace that contains the configuration file.
You can use the other providers without setting up access rights.
You can supply connector configuration for Kafka Connect or MirrorMaker 2 in this way by doing the following:
-
Mount config maps or secrets into the Kafka Connect pod as environment variables or volumes
-
Enable EnvVarConfigProvider
, FileConfigProvider
, or DirectoryConfigProvider
in the Kafka Connect or MirrorMaker 2 configuration
-
Pass connector configuration using the externalConfiguration
property in the spec
of the KafkaConnect
or KafkaMirrorMaker2
resource
Using providers help prevent the passing of restricted information through the Kafka Connect REST interface.
You can use this approach in the following scenarios:
-
Mounting environment variables with the values a connector uses to connect and communicate with a data source
-
Mounting a properties file with values that are used to configure Kafka Connect connectors
-
Mounting files in a directory that contains values for the TLS truststore and keystore used by a connector
Note
|
A restart is required when using a new Secret or ConfigMap for a connector, which can disrupt other connectors.
|
Use the KubernetesSecretConfigProvider
to provide configuration properties from a secret or the KubernetesConfigMapConfigProvider
to provide configuration properties from a config map.
In this procedure, a config map provides configuration properties for a connector.
The properties are specified as key values of the config map.
The config map is mounted into the Kafka Connect pod as a volume.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a config map containing the connector configuration.
Example config map with connector properties
apiVersion: v1
kind: ConfigMap
metadata:
name: my-connector-configuration
data:
option1: value1
option2: value2
Procedure
-
Configure the KafkaConnect
resource.
The specification shown here can support loading values from config maps and secrets.
Example Kafka Connect configuration to use config maps and secrets
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
annotations:
strimzi.io/use-connector-resources: "true"
spec:
# ...
config:
# ...
config.providers: secrets,configmaps # (1)
config.providers.configmaps.class: io.strimzi.kafka.KubernetesConfigMapConfigProvider # (2)
config.providers.secrets.class: io.strimzi.kafka.KubernetesSecretConfigProvider # (3)
# ...
-
The alias for the configuration provider is used to define other configuration parameters.
The provider parameters use the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
KubernetesConfigMapConfigProvider
provides values from config maps.
-
KubernetesSecretConfigProvider
provides values from secrets.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Create a role that permits access to the values in the external config map.
Example role to access values from a config map
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: connector-configuration-role
rules:
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["my-connector-configuration"]
verbs: ["get"]
# ...
The rule gives the role permission to access the my-connector-configuration
config map.
-
Create a role binding to permit access to the namespace that contains the config map.
Example role binding to access the namespace that contains the config map
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: connector-configuration-role-binding
subjects:
- kind: ServiceAccount
name: my-connect-connect
namespace: my-project
roleRef:
kind: Role
name: connector-configuration-role
apiGroup: rbac.authorization.k8s.io
# ...
The role binding gives the role permission to access the my-project
namespace.
The service account must be the same one used by the Kafka Connect deployment.
The service account name format is <cluster_name>-connect
, where <cluster_name>
is the name of the KafkaConnect
custom resource.
-
Reference the config map in the connector configuration.
Example connector configuration referencing the config map
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-connector
labels:
strimzi.io/cluster: my-connect
spec:
# ...
config:
option: ${configmaps:my-project/my-connector-configuration:option1}
# ...
# ...
The placeholder structure is configmaps:<path_and_file_name>:<property>
.
KubernetesConfigMapConfigProvider
reads and extracts the option1
property value from the external config map.
Use the EnvVarConfigProvider
to provide configuration properties as environment variables.
Environment variables can contain values from config maps or secrets.
In this procedure, environment variables provide configuration properties for a connector to communicate with Amazon AWS.
The connector must be able to read the AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
.
The values of the environment variables are derived from a secret mounted into the Kafka Connect pod.
Note
|
The names of user-defined environment variables cannot start with KAFKA_ or STRIMZI_ .
|
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the connector configuration.
Example secret with values for environment variables
apiVersion: v1
kind: Secret
metadata:
name: aws-creds
type: Opaque
data:
awsAccessKey: QUtJQVhYWFhYWFhYWFhYWFg=
awsSecretAccessKey: Ylhsd1lYTnpkMjl5WkE=
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use external environment variables
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
annotations:
strimzi.io/use-connector-resources: "true"
spec:
# ...
config:
# ...
config.providers: env # (1)
config.providers.env.class: org.apache.kafka.common.config.provider.EnvVarConfigProvider # (2)
# ...
externalConfiguration:
env:
- name: AWS_ACCESS_KEY_ID # (3)
valueFrom:
secretKeyRef:
name: aws-creds # (4)
key: awsAccessKey # (5)
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-creds
key: awsSecretAccessKey
# ...
-
The alias for the configuration provider is used to define other configuration parameters.
The provider parameters use the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
EnvVarConfigProvider
provides values from environment variables.
-
The environment variable takes a value from the secret.
-
The name of the secret containing the environment variable.
-
The name of the key stored in the secret.
Note
|
The secretKeyRef property references keys in a secret.
If you are using a config map instead of a secret, use the configMapKeyRef property.
|
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Reference the environment variable in the connector configuration.
Example connector configuration referencing the environment variable
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-connector
labels:
strimzi.io/cluster: my-connect
spec:
# ...
config:
option: ${env:AWS_ACCESS_KEY_ID}
option: ${env:AWS_SECRET_ACCESS_KEY}
# ...
# ...
The placeholder structure is env:<environment_variable_name>
.
EnvVarConfigProvider
reads and extracts the environment variable values from the mounted secret.
Use the FileConfigProvider
to provide configuration properties from a file within a directory.
Files can be config maps or secrets.
In this procedure, a file provides configuration properties for a connector.
A database name and password are specified as properties of a secret.
The secret is mounted to the Kafka Connect pod as a volume.
Volumes are mounted on the path /opt/kafka/external-configuration/<volume-name>
.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the connector configuration.
Example secret with database properties
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
stringData:
connector.properties: |- # (1)
dbUsername: my-username # (2)
dbPassword: my-password
-
The connector configuration in properties file format.
-
Database username and password properties used in the configuration.
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use an external property file
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
# ...
config:
config.providers: file # (1)
config.providers.file.class: org.apache.kafka.common.config.provider.FileConfigProvider # (2)
#...
externalConfiguration:
volumes:
- name: connector-config # (3)
secret:
secretName: mysecret # (4)
-
The alias for the configuration provider is used to define other configuration parameters.
-
FileConfigProvider
provides values from properties files.
The parameter uses the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
The name of the volume containing the secret.
-
The name of the secret.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Reference the file properties in the connector configuration as placeholders.
Example connector configuration referencing the file
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: io.debezium.connector.mysql.MySqlConnector
tasksMax: 2
config:
database.hostname: 192.168.99.1
database.port: "3306"
database.user: "${file:/opt/kafka/external-configuration/connector-config/mysecret:dbUsername}"
database.password: "${file:/opt/kafka/external-configuration/connector-config/mysecret:dbPassword}"
database.server.id: "184054"
#...
The placeholder structure is file:<path_and_file_name>:<property>
.
FileConfigProvider
reads and extracts the database username and password property values from the mounted secret.
Use the DirectoryConfigProvider
to provide configuration properties from multiple files within a directory.
Files can be config maps or secrets.
In this procedure, a secret provides the TLS keystore and truststore user credentials for a connector.
The credentials are in separate files.
The secrets are mounted into the Kafka Connect pod as volumes.
Volumes are mounted on the path /opt/kafka/external-configuration/<volume-name>
.
Prerequisites
-
A Kafka cluster is running.
-
The Cluster Operator is running.
-
You have a secret containing the user credentials.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
The my-user
secret provides the keystore credentials (user.crt
and user.key
) for the connector.
The <cluster_name>-cluster-ca-cert
secret generated when deploying the Kafka cluster provides the cluster CA certificate as truststore credentials (ca.crt
).
Procedure
-
Configure the KafkaConnect
resource.
Example Kafka Connect configuration to use external property files
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect
spec:
# ...
config:
config.providers: directory # (1)
config.providers.directory.class: org.apache.kafka.common.config.provider.DirectoryConfigProvider # (2)
#...
externalConfiguration:
volumes: # (3)
- name: cluster-ca # (4)
secret:
secretName: my-cluster-cluster-ca-cert # (5)
- name: my-user
secret:
secretName: my-user # (6)
-
The alias for the configuration provider is used to define other configuration parameters.
-
DirectoryConfigProvider
provides values from files in a directory. The parameter uses the alias from config.providers
, taking the form config.providers.${alias}.class
.
-
The names of the volumes containing the secrets.
-
The name of the secret for the cluster CA certificate to supply truststore configuration.
-
The name of the secret for the user to supply keystore configuration.
-
Create or update the resource to enable the provider.
kubectl apply -f <kafka_connect_configuration_file>
-
Reference the file properties in the connector configuration as placeholders.
Example connector configuration referencing the files
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: io.debezium.connector.mysql.MySqlConnector
tasksMax: 2
config:
# ...
database.history.producer.security.protocol: SSL
database.history.producer.ssl.truststore.type: PEM
database.history.producer.ssl.truststore.certificates: "${directory:/opt/kafka/external-configuration/cluster-ca:ca.crt}"
database.history.producer.ssl.keystore.type: PEM
database.history.producer.ssl.keystore.certificate.chain: "${directory:/opt/kafka/external-configuration/my-user:user.crt}"
database.history.producer.ssl.keystore.key: "${directory:/opt/kafka/external-configuration/my-user:user.key}"
#...
The placeholder structure is directory:<path>:<file_name>
.
DirectoryConfigProvider
reads and extracts the credentials from the mounted secrets.
A Strimzi deployment creates Kubernetes resources, such as Deployment
, Pod
, and Service
resources.
These resources are managed by Strimzi operators.
Only the operator that is responsible for managing a particular Kubernetes resource can change that resource.
If you try to manually change an operator-managed Kubernetes resource, the operator will revert your changes back.
Changing an operator-managed Kubernetes resource can be useful if you want to perform certain tasks, such as the following:
To make the changes to a Kubernetes resource, you can use the template
property within the spec
section of various Strimzi custom resources.
Here is a list of the custom resources where you can apply the changes:
The Strimzi Custom Resource API Reference provides more details about the customizable fields.
In the following example, the template
property is used to modify the labels in a Kafka broker’s pod.
Example template customization
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
labels:
app: my-cluster
spec:
kafka:
# ...
template:
pod:
metadata:
labels:
mylabel: myvalue
# ...
Strimzi allows you to customize the image pull policy for containers in all pods deployed by the Cluster Operator.
The image pull policy is configured using the environment variable STRIMZI_IMAGE_PULL_POLICY
in the Cluster Operator deployment.
The STRIMZI_IMAGE_PULL_POLICY
environment variable can be set to three different values:
Always
-
Container images are pulled from the registry every time the pod is started or restarted.
IfNotPresent
-
Container images are pulled from the registry only when they were not pulled before.
Never
-
Container images are never pulled from the registry.
Currently, the image pull policy can only be customized for all Kafka, Kafka Connect, and Kafka MirrorMaker clusters at once.
Changing the policy will result in a rolling update of all your Kafka, Kafka Connect, and Kafka MirrorMaker clusters.
Apply a termination grace period to give a Kafka cluster enough time to shut down cleanly.
Specify the time using the terminationGracePeriodSeconds
property.
Add the property to the template.pod
configuration of the Kafka
custom resource.
The time you add will depend on the size of your Kafka cluster.
The Kubernetes default for the termination grace period is 30 seconds.
If you observe that your clusters are not shutting down cleanly, you can increase the termination grace period.
A termination grace period is applied every time a pod is restarted.
The period begins when Kubernetes sends a term (termination) signal to the processes running in the pod.
The period should reflect the amount of time required to transfer the processes of the terminating pod to another pod before they are stopped.
After the period ends, a kill signal stops any processes still running in the pod.
The following example adds a termination grace period of 120 seconds to the Kafka
custom resource.
You can also specify the configuration in the custom resources of other Kafka components.
Example termination grace period configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
template:
pod:
terminationGracePeriodSeconds: 120
# ...
# ...
</div>
</div>
The KafkaTopic
resource configures topics, including partition and replication factor settings.
When you create, modify, or delete a topic using KafkaTopic
, the Topic Operator ensures that these changes are reflected in the Kafka cluster.
The KafkaTopic
resource is responsible for managing a single topic within a Kafka cluster.
The Topic Operator operates as follows:
-
When a KafkaTopic
is created, deleted, or changed, the Topic Operator performs the corresponding operation on the Kafka topic.
If a topic is created, deleted, or modified directly within the Kafka cluster, without the presence of a corresponding KafkaTopic
resource, the Topic Operator does not manage that topic.
The Topic Operator will only manage Kafka topics associated with KafkaTopic
resources and does not interfere with topics managed independently within the Kafka cluster.
If a KafkaTopic
does exist for a Kafka topic, any configuration changes made outside the resource are reverted.
The Topic Operator can detect cases where where multiple KafkaTopic
resources are attempting to manage a Kafka topic using the same .spec.topicName
.
Only the oldest resource is reconciled, while the other resources fail with a resource conflict error.
A KafkaTopic
resource includes a name for the topic and a label that identifies the name of the Kafka cluster it belongs to.
Label identifying a Kafka cluster for topic handling
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: topic-name-1
labels:
strimzi.io/cluster: my-cluster
spec:
topicName: topic-name-1
The label provides the cluster name of the Kafka
resource.
The Topic Operator uses the label as a mechanism for determining which KafkaTopic
resources to manage.
If the label does not match the Kafka cluster, the Topic Operator cannot see the KafkaTopic
, and the topic is not created.
Kafka and Kubernetes have their own naming validation rules, and a Kafka topic name might not be a valid resource name in Kubernetes.
If possible, try and stick to a naming convention that works for both.
Consider the following guidelines:
-
Use topic names that reflect the nature of the topic
-
Be concise and keep the name under 63 characters
-
Use all lower case and hyphens
-
Avoid special characters, spaces or symbols
The KafkaTopic
resource allows you to specify the Kafka topic name using the metadata.name
field.
However, if the desired Kafka topic name is not a valid Kubernetes resource name, you can use the spec.topicName
property to specify the actual name.
The spec.topicName
field is optional, and when it’s absent, the Kafka topic name defaults to the metadata.name
of the topic.
When a topic is created, the topic name cannot be changed later.
Example of supplying a valid Kafka topic name
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1 # (1)
spec:
topicName: My.Topic.1 # (2)
# ...
-
A valid topic name that works in Kubernetes.
-
A Kafka topic name that uses upper case and periods, which are invalid in Kubernetes.
If more than one KafkaTopic
resource refers to the same Kafka topic, the resource that was created first is considered to be the one managing the topic.
The status of the newer resources is updated to indicate a conflict, and their Ready
status is changed to False
.
A Kafka client application, such as Kafka Streams, can automatically create topics with invalid Kubernetes resource names.
If you want to manage these topics, you must create KafkaTopic
resources with a different .metadata.name
, as shown in the previous example.
Note
|
For more information on the requirements for identifiers and names in a cluster, refer to the Kubernetes documentation Object Names and IDs.
|
Configuration changes only go in one direction: from the KafkaTopic
resource to the Kafka topic.
Any changes to a Kafka topic managed outside the KafkaTopic
resource are reverted.
If you are reverting back to a version of Strimzi earlier than 0.41, which uses internal topics for the storage of topic metadata, you still downgrade your Cluster Operator to the previous version, then downgrade Kafka brokers and client applications to the previous Kafka version as standard.
If you are reverting back to a version of Strimzi earlier than 0.22, which uses ZooKeeper for the storage of topic metadata, you still downgrade your Cluster Operator to the previous version, then downgrade Kafka brokers and client applications to the previous Kafka version as standard.
However, you must also delete the topics that were created for the topic store using a kafka-topics
command, specifying the bootstrap address of the Kafka cluster.
For example:
kubectl run kafka-admin -ti --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 --rm=true --restart=Never -- ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi-topic-operator-kstreams-topic-store-changelog --delete && ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi_store_topic --delete
The command must correspond to the type of listener and authentication used to access the Kafka cluster.
The Topic Operator will reconstruct the ZooKeeper topic metadata from the state of the topics in Kafka.
Applications can trigger the automatic creation of topics in the Kafka cluster.
By default, the Kafka broker configuration auto.create.topics.enable
is set to true
, allowing the broker to create topics automatically when an application attempts to produce or consume from a non-existing topic.
Applications might also use the Kafka AdminClient
to automatically create topics.
When an application is deployed along with its KafkaTopic
resources, it is possible that automatic topic creation in the cluster happens before the Topic Operator can react to the KafkaTopic
.
The topics created for an application deployment are initially created with default topic configuration.
If the Topic Operator attempts to reconfigure the topics based on KafkaTopic
resource specifications included with the application deployment, the operation might fail because the required change to the configuration is not allowed.
For example, if the change means lowering the number of topic partitions.
For this reason, it is recommended to disable auto.create.topics.enable
in the Kafka cluster configuration.
Use the properties of the KafkaTopic
resource to configure Kafka topics.
Changes made to topic configuration in the KafkaTopic
are propagated to Kafka.
You can use kubectl apply
to create or modify topics, and kubectl delete
to delete existing topics.
To be able to delete topics, delete.topic.enable
must be set to true
(default) in the spec.kafka.config
of the Kafka resource.
This procedure shows how to create a topic with 10 partitions and 2 replicas.
Before you begin
The KafkaTopic resource does not allow the following changes:
-
Renaming the topic defined in spec.topicName
. A mismatch between spec.topicName
and status.topicName
will be detected.
-
Decreasing the number of partitions using spec.partitions
(not supported by Kafka).
-
Modifying the number of replicas specified in spec.replicas
.
Warning
|
Increasing spec.partitions for topics with keys will alter the partitioning of records, which can cause issues, especially when the topic uses semantic partitioning.
|
Prerequisites
-
A running Kafka cluster configured with a Kafka broker listener using mTLS authentication and TLS encryption.
-
A running Topic Operator (typically deployed with the Entity Operator).
-
For deleting a topic, delete.topic.enable=true
(default) in the spec.kafka.config
of the Kafka
resource.
Procedure
-
Configure the KafkaTopic
resource.
Example Kafka topic configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
Tip
|
When modifying a topic, you can get the current version of the resource using kubectl get kafkatopic my-topic-1 -o yaml .
|
-
Create the KafkaTopic
resource in Kubernetes.
kubectl apply -f <topic_config_file>
-
Wait for the ready status of the topic to change to True
:
kubectl get kafkatopics -o wide -w -n <namespace>
Kafka topic status
NAME CLUSTER PARTITIONS REPLICATION FACTOR READY
my-topic-1 my-cluster 10 3 True
my-topic-2 my-cluster 10 3
my-topic-3 my-cluster 10 3 True
Topic creation is successful when the READY
output shows True
.
-
If the READY
column stays blank, get more details on the status from the resource YAML or from the Topic Operator logs.
Status messages provide details on the reason for the current status.
oc get kafkatopics my-topic-2 -o yaml
Details on a topic with a NotReady
status
# ...
status:
conditions:
- lastTransitionTime: "2022-06-13T10:14:43.351550Z"
message: Number of partitions cannot be decreased
reason: PartitionDecreaseException
status: "True"
type: NotReady
In this example, the reason the topic is not ready is because the original number of partitions was reduced in the KafkaTopic
configuration.
Kafka does not support this.
After resetting the topic configuration, the status shows the topic is ready.
kubectl get kafkatopics my-topic-2 -o wide -w -n <namespace>
Status update of the topic
NAME CLUSTER PARTITIONS REPLICATION FACTOR READY
my-topic-2 my-cluster 10 3 True
Fetching the details shows no messages
kubectl get kafkatopics my-topic-2 -o yaml
Details on a topic with a READY
status
# ...
status:
conditions:
- lastTransitionTime: '2022-06-13T10:15:03.761084Z'
status: 'True'
type: Ready
The recommended configuration for topics managed by the Topic Operator is a topic replication factor of 3, and a minimum of 2 in-sync replicas.
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10 # (1)
replicas: 3 # (2)
config:
min.insync.replicas: 2 # (3)
#...
-
The number of partitions for the topic.
-
The number of replica topic partitions. Changing the number of replicas in the topic configuration requires a deployment of Cruise Control.
For more information, see Using Cruise Control to modify topic replication factor.
-
The minimum number of replica partitions that a message must be successfully written to, or an exception is raised.
Note
|
In-sync replicas are used in conjunction with the acks configuration for producer applications.
The acks configuration determines the number of follower partitions a message must be replicated to before the message is acknowledged as successfully received.
Replicas need to be reassigned when adding or removing brokers (see Scaling clusters by adding or removing brokers).
|
This procedure describes how to convert Kafka topics that are currently managed through the KafkaTopic
resource into non-managed topics.
This capability can be useful in various scenarios.
For instance, you might want to update the metadata.name
of a KafkaTopic
resource.
You can only do that by deleting the original KafkaTopic
resource and recreating a new one.
By annotating a KafkaTopic
resource with strimzi.io/managed=false
, you indicate that the Topic Operator should no longer manage that particular topic.
This allows you to retain the Kafka topic while making changes to the resource’s configuration or other administrative tasks.
Procedure
-
Annotate the KafkaTopic
resource in Kubernetes, setting strimzi.io/managed
to false
:
kubectl annotate kafkatopic my-topic-1 strimzi.io/managed="false"
Specify the metadata.name
of the topic in your KafkaTopic
resource, which is my-topic-1
in this example.
-
Check the status of the KafkaTopic
resource to make sure the request was successful:
oc get kafkatopics my-topic-1 -o yaml
Example topic with a Ready
status
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 124
name: my-topic-1
finalizer:
strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
# ...
status:
observedGeneration: 124 # (1)
topicName: my-topic-1
conditions:
- type: Ready
status: True
lastTransitionTime: 20230301T103000Z
-
Successful reconciliation of the resource means the topic is no longer managed.
The value of metadata.generation
(the current version of the deployment) must match status.observedGeneration
(the latest reconciliation of the resource).
-
You can now make changes to the KafkaTopic
resource without it affecting the Kafka topic it was managing.
For example, to change the metadata.name
, do as follows:
-
Delete the original KafkTopic
resource:
kubectl delete kafkatopic <kafka_topic_name>
-
Recreate the KafkTopic
resource with a different metadata.name
, but use spec.topicName
to refer to the same topic that was managed by the original
-
If you haven’t deleted the original KafkaTopic
resource, and you wish to resume management of the Kafka topic again, set the strimzi.io/managed
annotation to true
or remove the annotation.
This procedure describes how to enable topic management for topics that are not currently managed through the KafkaTopic
resource.
You do this by creating a matching KafkaTopic
resource.
Procedure
-
Create a KafkaTopic
resource with a metadata.name
that is the same as the Kafka topic.
Or use spec.topicName
if the name of the topic in Kafka would not be a legal Kubernetes resource name.
Example Kafka topic configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic-1
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
In this example, the Kafka topic is named my-topic-1
.
The Topic Operator checks whether the topic is managed by another KafkaTopic
resource.
If it is, the older resource takes precedence and a resource conflict error is returned in the status of the new resource.
-
Apply the KafkaTopic
resource:
kubectl apply -f <topic_configuration_file>
-
Wait for the operator to update the topic in Kafka.
The operator updates the Kafka topic with the spec
of the KafkaTopic
that has the same name.
-
Check the status of the KafkaTopic
resource to make sure the request was successful:
oc get kafkatopics my-topic-1 -o yaml
Example topic with a Ready
status
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 2
# ...
status:
observedGeneration: 1 # (1)
topicName: my-topic-1
conditions:
- type: Ready
status: True
lastTransitionTime: 20230301T103000Z
-
Successful reconciliation of the resource means the topic is now managed.
The value of metadata.generation
(the current version of the deployment) must match status.observedGeneration
(the latest reconciliation of the resource).
The Topic Operator supports the deletion of topics managed through the KafkaTopic
resource with or without Kubernetes finalizers.
This is determined by the STRIMZI_USE_FINALIZERS
Topic Operator environment variable.
By default, this is set to true
, though it can be set to false
in the Topic Operator env
configuration if you do not want the Topic Operator to add finalizers.
Finalizers ensure orderly and controlled deletion of KafkaTopic
resources.
A finalizer for the Topic Operator is added to the metadata of the KafkaTopic
resource:
Finalizer to control topic deletion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
finalizers:
- strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
In this example, the finalizer is added for topic my-topic-1
.
The finalizer prevents the topic from being fully deleted until the finalization process is complete.
If you then delete the topic using kubectl delete kafkatopic my-topic-1
, a timestamp is added to the metadata:
Finalizer timestamp on deletion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
generation: 1
name: my-topic-1
finalizers:
- strimzi.io/topic-operator
labels:
strimzi.io/cluster: my-cluster
deletionTimestamp: 20230301T000000.000
The resource is still present.
If the deletion fails, it is shown in the status of the resource.
When the finalization tasks are successfully executed, the finalizer is removed from the metadata, and the resource is fully deleted.
Finalizers also serve to prevent related resources from being deleted.
If the Topic Operator is not running, it won’t be able to remove its finalizer from the metadata.finalizers
.
And any attempt to directly delete the KafkaTopic
resources or the namespace will fail or timeout, leaving the namespace in a stuck terminating state.
If this happens, you can bypass the finalization process by removing the finalizers on topics.
If the Topic Operator is not running, and you want to bypass the finalization process when deleting managed topics, you must remove the finalizers.
You can do this manually by editing the resources directly or by using a command.
To remove finalizers on all topics, use the following command:
Removing finalizers on topics
kubectl get kt -o=json | jq '.items[].metadata.finalizers = null' | kubectl apply -f -
The command uses the jq
command line JSON parser tool to modify the KafkaTopic
(kt
) resources by setting the finalizers to null
.
You can also use the command for a specific topic:
Removing a finalizer on a specific topic
kubectl get kt <topic_name> -o=json | jq '.metadata.finalizers = null' | kubectl apply -f -
After running the command, you can go ahead and delete the topics.
Alternatively, if the topics were already being deleted but were blocked due to outstanding finalizers then their deletion should complete.
Warning
|
Be careful when removing finalizers, as any cleanup operations associated with the finalization process are not performed if the Topic Operator is not running.
For example, if you remove the finalizer from a KafkaTopic resource and subsequently delete the resource, the related Kafka topic won’t be deleted.
|
When the delete.topic.enable
configuration in Kafka is set to false
, topics cannot be deleted.
This might be required in certain scenarios, but it introduces a consideration when using the Topic Operator.
As topics cannot be deleted, finalizers added to the metadata of a KafkaTopic
resource to control topic deletion are never removed by the Topic Operator (though they can be removed manually).
Similarly, any Custom Resource Definitions (CRDs) or namespaces associated with topics cannot be deleted.
Before configuring delete.topic.enable=false
, assess these implications to ensure it aligns with your specific requirements.
Note
|
To avoid using finalizers, you can set the STRIMZI_USE_FINALIZERS Topic Operator environment variable to false .
|
The Topic Operator uses the request batching capabilities of the Kafka Admin API for operations on topic resources.
You can fine-tune the batching mechanism using the following operator configuration properties:
-
STRIMZI_MAX_QUEUE_SIZE
to set the maximum size of the topic event queue.
The default value is 1024.
-
STRIMZI_MAX_BATCH_SIZE
to set the maximum number of topic events allowed in a single batch.
The default value is 100.
-
MAX_BATCH_LINGER_MS
to specify the maximum time to wait for a batch to accumulate items before processing.
The default is 100 milliseconds.
If the maximum size of the request batching queue is exceeded, the Topic Operator shuts down and is restarted.
To prevent frequent restarts, consider adjusting the STRIMZI_MAX_QUEUE_SIZE
property to accommodate the typical load.
When you create, modify or delete a user using the KafkaUser
resource,
the User Operator ensures that these changes are reflected in the Kafka cluster.
Use the properties of the KafkaUser
resource to configure Kafka users.
You can use kubectl apply
to create or modify users, and kubectl delete
to delete existing users.
Users represent Kafka clients.
When you configure Kafka users, you enable the user authentication and authorization mechanisms required by clients to access Kafka.
The mechanism used must match the equivalent Kafka
configuration.
For more information on using Kafka
and KafkaUser
resources to secure access to Kafka brokers, see Securing access to a Kafka cluster.
Procedure
-
Configure the KafkaUser
resource.
This example specifies mTLS authentication and simple authorization using ACLs.
Example Kafka user configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user-1
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: tls
authorization:
type: simple
acls:
# Example consumer Acls for topic my-topic using consumer group my-group
- resource:
type: topic
name: my-topic
patternType: literal
operations:
- Describe
- Read
host: "*"
- resource:
type: group
name: my-group
patternType: literal
operations:
- Read
host: "*"
# Example Producer Acls for topic my-topic
- resource:
type: topic
name: my-topic
patternType: literal
operations:
- Create
- Describe
- Write
host: "*"
-
Create the KafkaUser
resource in Kubernetes.
kubectl apply -f <user_config_file>
-
Wait for the ready status of the user to change to True
:
kubectl get kafkausers -o wide -w -n <namespace>
Kafka user status
NAME CLUSTER AUTHENTICATION AUTHORIZATION READY
my-user-1 my-cluster tls simple True
my-user-2 my-cluster tls simple
my-user-3 my-cluster tls simple True
User creation is successful when the READY
output shows True
.
-
If the READY
column stays blank, get more details on the status from the resource YAML or User Operator logs.
Messages provide details on the reason for the current status.
kubectl get kafkausers my-user-2 -o yaml
Details on a user with a NotReady
status
# ...
status:
conditions:
- lastTransitionTime: "2022-06-10T10:07:37.238065Z"
message: Simple authorization ACL rules are configured but not supported in the
Kafka cluster configuration.
reason: InvalidResourceException
status: "True"
type: NotReady
In this example, the reason the user is not ready is because simple authorization is not enabled in the Kafka
configuration.
Kafka configuration for simple authorization
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
authorization:
type: simple
After updating the Kafka configuration, the status shows the user is ready.
kubectl get kafkausers my-user-2 -o wide -w -n <namespace>
Status update of the user
NAME CLUSTER AUTHENTICATION AUTHORIZATION READY
my-user-2 my-cluster tls simple True
Fetching the details shows no messages.
kubectl get kafkausers my-user-2 -o yaml
Details on a user with a READY
status
# ...
status:
conditions:
- lastTransitionTime: "2022-06-10T10:33:40.166846Z"
status: "True"
type: Ready
After you have deployed Strimzi, you can set up client access to your Kafka cluster.
To verify the deployment, you can deploy example producer and consumer clients.
Otherwise, create listeners that provide client access within or outside the Kubernetes cluster.
Send and receive messages from a Kafka cluster installed on Kubernetes.
This procedure describes how to deploy Kafka clients to the Kubernetes cluster, then produce and consume messages to test your installation.
The clients are deployed using the Kafka container image.
Procedure
-
Deploy a Kafka producer.
This example deploys a Kafka producer that connects to the Kafka cluster my-cluster
.
A topic named my-topic
is created.
Deploying a Kafka producer to Kubernetes
kubectl run kafka-producer -ti --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 --rm=true --restart=Never -- bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic
-
Type a message into the console where the producer is running.
-
Press Enter to send the message.
-
Deploy a Kafka consumer.
The consumer should consume messages produced to my-topic
in the Kafka cluster my-cluster
.
Deploying a Kafka consumer to Kubernetes
kubectl run kafka-consumer -ti --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 --rm=true --restart=Never -- bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic --from-beginning
-
Confirm that you see the incoming messages in the consumer console.
Use listeners to enable client connections to Kafka.
Strimzi provides a generic GenericKafkaListener
schema with properties to configure listeners through the Kafka
resource.
When configuring a Kafka cluster, you specify a listener type
based on your requirements, environment, and infrastructure.
Services, routes, load balancers, and ingresses for clients to connect to a cluster are created according to the listener type.
Internal and external listener types are supported.
- Internal listeners
-
Use internal listener types to connect clients within a kubernetes cluster.
- External listeners
-
Use external listener types to connect clients outside a Kubernetes cluster.
-
nodeport
to use ports on Kubernetes nodes
-
loadbalancer
to use loadbalancer services
-
ingress
to use Kubernetes Ingress
and the Ingress NGINX Controller for Kubernetes (Kubernetes only)
-
route
to use OpenShift Route
and the default HAProxy router (OpenShift only)
External listeners handle access to a Kafka cluster from networks that require different authentication mechanisms.
For example, loadbalancers might not be suitable for certain infrastructure, such as bare metal, where node ports provide a better option.
Important
|
Do not use the built-in ingress controller on OpenShift, use the route type instead. The Ingress NGINX Controller is only intended for use on Kubernetes. The route type is only supported on OpenShift.
|
Each listener is defined as an array in the Kafka
resource.
Example listener configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
configuration:
useServiceDnsDomain: true
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
- name: external1
port: 9094
type: route
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-certificate.crt
key: my-key.key
# ...
You can configure as many listeners as required, as long as their names and ports are unique.
You can also configure listeners for secure connection using authentication.
Note
|
If you scale your Kafka cluster while using external listeners, it might trigger a rolling update of all Kafka brokers. This depends on the configuration.
|
From the listener configuration, the resulting listener bootstrap and per-broker service names are structured according to the following naming conventions:
Table 17. Listener naming conventions
Listener type |
Bootstrap service name |
Per-Broker service name |
|
<cluster_name>-kafka-bootstrap |
Not applicable |
loadbalancer
nodeport
ingress
route
cluster-ip
|
<cluster_name>-kafka-<listener-name>-bootstrap |
<cluster_name>-kafka-<listener-name>-<idx> |
For example, my-cluster-kafka-bootstrap
, my-cluster-kafka-external1-bootstrap
, and my-cluster-kafka-external1-0
.
The names are assigned to the services, routes, load balancers, and ingresses created through the listener configuration.
You can use certain backwards compatible names and port numbers to transition listeners initially configured under the retired KafkaListeners
schema.
The resulting external listener naming convention varies slightly.
The specific combinations of listener name and port configuration values in the following table are backwards compatible.
Table 18. Backwards compatible listener name and port combinations
Listener name |
Port |
Bootstrap service name |
Per-Broker service name |
|
|
<cluster_name>-kafka-bootstrap |
Not applicable |
|
|
<cluster-name>-kafka-bootstrap |
Not applicable |
|
|
<cluster_name>-kafka-bootstrap |
<cluster_name>-kafka-bootstrap-<idx> |
Use node ports to access a Kafka cluster from an external client outside the Kubernetes cluster.
To connect to a broker, you specify a hostname and port number for the Kafka bootstrap address, as well as the certificate used for TLS encryption.
The procedure shows basic nodeport
listener configuration.
You can use listener properties to enable TLS encryption (tls
) and specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the following configuration properties with nodeport
listeners:
preferredNodePortAddressType
-
Specifies the first address type that’s checked as the node address.
externalTrafficPolicy
-
Specifies whether the service routes external traffic to node-local or cluster-wide endpoints.
nodePort
-
Overrides the assigned node port numbers for the bootstrap and broker services.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external4
.
Procedure
-
Configure a Kafka
resource with an external listener set to the nodeport
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external4
port: 9094
type: nodeport
tls: true
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
NodePort
type services are created for each Kafka broker, as well as an external bootstrap service.
Node port services created for the bootstrap and brokers
NAME TYPE CLUSTER-IP PORT(S)
my-cluster-kafka-external4-0 NodePort 172.30.55.13 9094:31789/TCP
my-cluster-kafka-external4-1 NodePort 172.30.250.248 9094:30028/TCP
my-cluster-kafka-external4-2 NodePort 172.30.115.81 9094:32650/TCP
my-cluster-kafka-external4-bootstrap NodePort 172.30.30.23 9094:32650/TCP
The bootstrap address used for client connection is propagated to the status
of the Kafka
resource.
Example status for the bootstrap address
status:
clusterId: Y_RJQDGKRXmNF7fEcWldJQ
conditions:
- lastTransitionTime: '2023-01-31T14:59:37.113630Z'
status: 'True'
type: Ready
kafkaVersion: 3.8.0
listeners:
# ...
- addresses:
- host: ip-10-0-224-199.us-west-2.compute.internal
port: 32650
bootstrapServers: 'ip-10-0-224-199.us-west-2.compute.internal:32650'
certificates:
- |
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
name: external4
observedGeneration: 2
operatorLastSuccessfulVersion: 0.43.0
# ...
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external4")].bootstrapServers}{"\n"}'
ip-10-0-224-199.us-west-2.compute.internal:32650
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host and port in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, ip-10-0-224-199.us-west-2.compute.internal:32650
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
Use loadbalancers to access a Kafka cluster from an external client outside the Kubernetes cluster.
To connect to a broker, you specify a hostname and port number for the Kafka bootstrap address, as well as the certificate used for TLS encryption.
The procedure shows basic loadbalancer
listener configuration.
You can use listener properties to enable TLS encryption (tls
) and specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the following configuration properties with loadbalancer
listeners:
loadBalancerSourceRanges
-
Restricts traffic to a specified list of CIDR (Classless Inter-Domain Routing) ranges.
externalTrafficPolicy
-
Specifies whether the service routes external traffic to node-local or cluster-wide endpoints.
loadBalancerIP
-
Requests a specific IP address when creating a loadbalancer.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external3
.
Procedure
-
Configure a Kafka
resource with an external listener set to the loadbalancer
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is also created in the secret my-cluster-cluster-ca-cert
.
loadbalancer
type services and loadbalancers are created for each Kafka broker, as well as an external bootstrap service.
Loadbalancer services and loadbalancers created for the bootstraps and brokers
NAME TYPE CLUSTER-IP PORT(S)
my-cluster-kafka-external3-0 LoadBalancer 172.30.204.234 9094:30011/TCP
my-cluster-kafka-external3-1 LoadBalancer 172.30.164.89 9094:32544/TCP
my-cluster-kafka-external3-2 LoadBalancer 172.30.73.151 9094:32504/TCP
my-cluster-kafka-external3-bootstrap LoadBalancer 172.30.30.228 9094:30371/TCP
NAME EXTERNAL-IP (loadbalancer)
my-cluster-kafka-external3-0 a8a519e464b924000b6c0f0a05e19f0d-1132975133.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-1 ab6adc22b556343afb0db5ea05d07347-611832211.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-2 a9173e8ccb1914778aeb17eca98713c0-777597560.us-west-2.elb.amazonaws.com
my-cluster-kafka-external3-bootstrap a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
The bootstrap address used for client connection is propagated to the status
of the Kafka
resource.
Example status for the bootstrap address
status:
clusterId: Y_RJQDGKRXmNF7fEcWldJQ
conditions:
- lastTransitionTime: '2023-01-31T14:59:37.113630Z'
status: 'True'
type: Ready
kafkaVersion: 3.8.0
listeners:
# ...
- addresses:
- host: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
port: 9094
bootstrapServers: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
certificates:
- |
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
name: external3
observedGeneration: 2
operatorLastSuccessfulVersion: 0.43.0
# ...
The DNS addresses used for client connection are propagated to the status
of each loadbalancer service.
Example status for the bootstrap loadbalancer
status:
loadBalancer:
ingress:
- hostname: >-
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com
# ...
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external3")].bootstrapServers}{"\n"}'
a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host and port in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, a8d4a6fb363bf447fb6e475fc3040176-36312313.us-west-2.elb.amazonaws.com:9094
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
To be able to use an Ingress NGINX Controller for Kubernetes, add configuration for an ingress
type listener in the Kafka
custom resource.
When applied, the configuration creates a dedicated ingress and service for an external bootstrap and each broker in the cluster.
Clients connect to the bootstrap ingress, which routes them through the bootstrap service to connect to a broker.
Per-broker connections are then established using DNS names, which route traffic from the client to the broker through the broker-specific ingresses and services.
To connect to a broker, you specify a hostname for the ingress bootstrap address, as well as the certificate used for TLS encryption.
For access using an ingress, the port used in the Kafka client is typically 443.
The procedure shows basic ingress
listener configuration.
TLS encryption (tls
) must be enabled.
You can also specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the class
configuration property with ingress
listeners to specify the ingress controller used.
TLS passthrough
Make sure that you enable TLS passthrough in your Ingress NGINX Controller for Kubernetes deployment.
Kafka uses a binary protocol over TCP, but the Ingress NGINX Controller for Kubernetes is designed to work with a HTTP protocol.
To be able to route TCP traffic through ingresses, Strimzi uses TLS passthrough with Server Name Indication (SNI).
SNI helps with identifying and passing connection to Kafka brokers.
In passthrough mode, TLS encryption is always used.
Because the connection passes to the brokers, the listeners use the TLS certificates signed by the internal cluster CA and not the ingress certificates.
To configure listeners to use your own listener certificates, use the brokerCertChainAndKey
property.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external2
.
Procedure
-
Configure a Kafka
resource with an external listener set to the ingress
type.
Specify an ingress hostname for the bootstrap service and each of the Kafka brokers in the Kafka cluster.
Add any hostname to the bootstrap
and broker-<index>
prefixes that identify the bootstrap and brokers.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external2
port: 9094
type: ingress
tls: true # (1)
authentication:
type: tls
configuration:
bootstrap:
host: bootstrap.myingress.com
brokers:
- broker: 0
host: broker-0.myingress.com
- broker: 1
host: broker-1.myingress.com
- broker: 2
host: broker-2.myingress.com
class: nginx # (2)
# ...
zookeeper:
# ...
-
For ingress
type listeners, TLS encryption must be enabled (true
).
-
(Optional) Class that specifies the ingress controller to use. You might need to add a class if you have not set up a default and a class name is missing in the ingresses created.
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
ClusterIP
type services are created for each Kafka broker, as well as an external bootstrap service.
An ingress
is also created for each service, with a DNS address to expose them using the Ingress NGINX Controller for Kubernetes.
Ingresses created for the bootstrap and brokers
NAME CLASS HOSTS ADDRESS PORTS
my-cluster-kafka-external2-0 nginx broker-0.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-1 nginx broker-1.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-2 nginx broker-2.myingress.com 192.168.49.2 80,443
my-cluster-kafka-external2-bootstrap nginx bootstrap.myingress.com 192.168.49.2 80,443
The DNS addresses used for client connection are propagated to the status
of each ingress.
Status for the bootstrap ingress
status:
loadBalancer:
ingress:
- ip: 192.168.49.2
# ...
-
Use a target broker to check the client-server TLS connection on port 443 using the OpenSSL s_client
.
openssl s_client -connect broker-0.myingress.com:443 -servername broker-0.myingress.com -showcerts
The server name is the SNI for passing the connection to the broker.
If the connection is successful, the certificates for the broker are returned.
Certificates for the broker
Certificate chain
0 s:O = io.strimzi, CN = my-cluster-kafka
i:O = io.strimzi, CN = cluster-ca v0
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the bootstrap host (from the listener configuration
) and port 443 in your Kafka client as the bootstrap address to connect to the Kafka cluster. For example, bootstrap.myingress.com:443
.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
Use OpenShift routes to access a Kafka cluster from clients outside the OpenShift cluster.
To be able to use routes, add configuration for a route
type listener in the Kafka
custom resource.
When applied, the configuration creates a dedicated route and service for an external bootstrap and each broker in the cluster.
Clients connect to the bootstrap route, which routes them through the bootstrap service to connect to a broker.
Per-broker connections are then established using DNS names, which route traffic from the client to the broker through the broker-specific routes and services.
To connect to a broker, you specify a hostname for the route bootstrap address, as well as the certificate used for TLS encryption.
For access using routes, the port is always 443.
Warning
|
An OpenShift route address comprises the Kafka cluster name, the listener name, the project name, and the domain of the router.
For example, my-cluster-kafka-external1-bootstrap-my-project.domain.com (<cluster_name>-kafka-<listener_name>-bootstrap-<namespace>.<domain>).
Each DNS label (between periods “.”) must not exceed 63 characters, and the total length of the address must not exceed 255 characters.
|
The procedure shows basic listener configuration.
TLS encryption (tls
) must be enabled.
You can also specify a client authentication mechanism (authentication
).
Add additional configuration using configuration
properties.
For example, you can use the host
configuration property with route
listeners to specify the hostnames used by the bootstrap and per-broker services.
TLS passthrough
TLS passthrough is enabled for routes created by Strimzi.
Kafka uses a binary protocol over TCP, but routes are designed to work with a HTTP protocol.
To be able to route TCP traffic through routes, Strimzi uses TLS passthrough with Server Name Indication (SNI).
SNI helps with identifying and passing connection to Kafka brokers.
In passthrough mode, TLS encryption is always used.
Because the connection passes to the brokers, the listeners use TLS certificates signed by the internal cluster CA and not the ingress certificates.
To configure listeners to use your own listener certificates, use the brokerCertChainAndKey
property.
In this procedure, the Kafka cluster name is my-cluster
.
The name of the listener is external1
.
Procedure
-
Configure a Kafka
resource with an external listener set to the route
type.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
labels:
app: my-cluster
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external1
port: 9094
type: route
tls: true # (1)
authentication:
type: tls
# ...
# ...
zookeeper:
# ...
-
For route
type listeners, TLS encryption must be enabled (true
).
-
Create or update the resource.
kubectl apply -f <kafka_configuration_file>
A cluster CA certificate to verify the identity of the kafka brokers is created in the secret my-cluster-cluster-ca-cert
.
ClusterIP
type services are created for each Kafka broker, as well as an external bootstrap service.
A route
is also created for each service, with a DNS address (host/port) to expose them using the default OpenShift HAProxy router.
The routes are preconfigured with TLS passthrough.
Routes created for the bootstraps and brokers
NAME HOST/PORT SERVICES PORT TERMINATION
my-cluster-kafka-external1-0 my-cluster-kafka-external1-0-my-project.router.com my-cluster-kafka-external1-0 9094 passthrough
my-cluster-kafka-external1-1 my-cluster-kafka-external1-1-my-project.router.com my-cluster-kafka-external1-1 9094 passthrough
my-cluster-kafka-external1-2 my-cluster-kafka-external1-2-my-project.router.com my-cluster-kafka-external1-2 9094 passthrough
my-cluster-kafka-external1-bootstrap my-cluster-kafka-external1-bootstrap-my-project.router.com my-cluster-kafka-external1-bootstrap 9094 passthrough
The DNS addresses used for client connection are propagated to the status
of each route.
Example status for the bootstrap route
status:
ingress:
- host: >-
my-cluster-kafka-external1-bootstrap-my-project.router.com
# ...
-
Use a target broker to check the client-server TLS connection on port 443 using the OpenSSL s_client
.
openssl s_client -connect my-cluster-kafka-external1-0-my-project.router.com:443 -servername my-cluster-kafka-external1-0-my-project.router.com -showcerts
The server name is the Server Name Indication (SNI) for passing the connection to the broker.
If the connection is successful, the certificates for the broker are returned.
Certificates for the broker
Certificate chain
0 s:O = io.strimzi, CN = my-cluster-kafka
i:O = io.strimzi, CN = cluster-ca v0
-
Retrieve the address of the bootstrap service from the status of the Kafka
resource.
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external1")].bootstrapServers}{"\n"}'
my-cluster-kafka-external1-bootstrap-my-project.router.com:443
The address comprises the Kafka cluster name, the listener name, the project name and the domain of the router (router.com
in this example).
-
Extract the cluster CA certificate.
kubectl get secret my-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Configure your client to connect to the brokers.
-
Specify the address for the bootstrap service and port 443 in your Kafka client as the bootstrap address to connect to the Kafka cluster.
-
Add the extracted certificate to the truststore of your Kafka client to configure a TLS connection.
If you enabled a client authentication mechanism, you will also need to configure it in your client.
Note
|
If you are using your own listener certificates, check whether you need to add the CA certificate to the client’s truststore configuration.
If it is a public (external) CA, you usually won’t need to add it.
|
Service discovery makes it easier for client applications running in the same Kubernetes cluster as Strimzi to interact with a Kafka cluster.
A service discovery label and annotation are created for the following services:
Example internal Kafka bootstrap service
apiVersion: v1
kind: Service
metadata:
annotations:
strimzi.io/discovery: |-
[ {
"port" : 9092,
"tls" : false,
"protocol" : "kafka",
"auth" : "scram-sha-512"
}, {
"port" : 9093,
"tls" : true,
"protocol" : "kafka",
"auth" : "tls"
} ]
labels:
strimzi.io/cluster: my-cluster
strimzi.io/discovery: "true"
strimzi.io/kind: Kafka
strimzi.io/name: my-cluster-kafka-bootstrap
name: my-cluster-kafka-bootstrap
spec:
#...
Example Kafka Bridge service
apiVersion: v1
kind: Service
metadata:
annotations:
strimzi.io/discovery: |-
[ {
"port" : 8080,
"tls" : false,
"auth" : "none",
"protocol" : "http"
} ]
labels:
strimzi.io/cluster: my-bridge
strimzi.io/discovery: "true"
strimzi.io/kind: KafkaBridge
strimzi.io/name: my-bridge-bridge-service
Find services by specifying the discovery label when fetching services from the command line or a corresponding API call.
Returning services using the discovery label
kubectl get service -l strimzi.io/discovery=true
Connection details are returned when retrieving the service discovery label.
Secure connections by configuring Kafka and Kafka users.
Through configuration, you can implement encryption, authentication, and authorization mechanisms.
Kafka configuration
To establish secure access to Kafka, configure the Kafka
resource to set up the following configurations based on your specific requirements:
-
Listeners with specified authentication types to define how clients authenticate
-
Authorization for the entire Kafka cluster
-
Network policies for restricting access
-
Super users for unconstrained access to brokers
Authentication is configured independently for each listener, while authorization is set up for the whole Kafka cluster.
User (client-side) configuration
To enable secure client access to Kafka, configure KafkaUser
resources.
These resources represent clients and determine how they authenticate and authorize with the Kafka cluster.
Configure the KafkaUser
resource to set up the following configurations based on your specific requirements:
-
Authentication that must match the enabled listener authentication
-
Simple authorization to apply Access Control List (ACL) rules
-
Quotas to limit client access based on byte rates or CPU utilization
The User Operator creates the user representing the client and the security credentials used for client authentication, based on the chosen authentication type.
Configure client authentication for Kafka brokers when creating listeners.
Specify the listener authentication type using the Kafka.spec.kafka.listeners.authentication
property in the Kafka
resource.
For clients inside the Kubernetes cluster, you can create plain
(without encryption) or tls
internal listeners.
The internal
listener type use a headless service and the DNS names given to the broker pods.
As an alternative to the headless service, you can also create a cluster-ip
type of internal listener to expose Kafka using per-broker ClusterIP
services.
For clients outside the Kubernetes cluster, you create external listeners and specify a connection mechanism,
which can be nodeport
, loadbalancer
, ingress
(Kubernetes only), or route
(OpenShift only).
Supported authentication options:
If you’re using OAuth 2.0 for client access management, user authentication and authorization credentials are handled through the authorization server.
The authentication option you choose depends on how you wish to authenticate client access to Kafka brokers.
Note
|
Try exploring the standard authentication options before using custom authentication. Custom authentication allows for any type of Kafka-supported authentication. It can provide more flexibility, but also adds complexity.
|
Figure 4. Kafka listener authentication options
The listener authentication
property is used to specify an authentication mechanism specific to that listener.
If no authentication
property is specified then the listener does not authenticate clients which connect through that listener.
The listener will accept all connections without authentication.
Authentication must be configured when using the User Operator to manage KafkaUsers
.
The following example shows:
-
A plain
listener configured for SCRAM-SHA-512 authentication
-
A tls
listener with mTLS authentication
-
An external
listener with mTLS authentication
Each listener is configured with a unique name and port within a Kafka cluster.
Important
|
When configuring listeners for client access to brokers, you can use port 9092 or higher (9093, 9094, and so on), but with a few exceptions.
The listeners cannot be configured to use the ports reserved for interbroker communication (9090 and 9091), Prometheus metrics (9404), and JMX (Java Management Extensions) monitoring (9999).
|
Example listener authentication configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: true
authentication:
type: scram-sha-512
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: tls
# ...
mTLS authentication is always used for the communication between Kafka brokers and ZooKeeper pods.
Strimzi can configure Kafka to use TLS (Transport Layer Security) to provide encrypted communication between Kafka brokers and clients either with or without mutual authentication.
For mutual, or two-way, authentication, both the server and the client present certificates.
When you configure mTLS authentication, the broker authenticates the client (client authentication) and the client authenticates the broker (server authentication).
mTLS listener configuration in the Kafka
resource requires the following:
When a Kafka cluster is created by the Cluster Operator, it creates a new secret with the name <cluster_name>-cluster-ca-cert
.
The secret contains a CA certificate.
The CA certificate is in PEM and PKCS #12 format.
To verify a Kafka cluster, add the CA certificate to the truststore in your client configuration.
To verify a client, add a user certificate and key to the keystore in your client configuration.
For more information on configuring a client for mTLS, see Configuring user authentication.
Note
|
TLS authentication is more commonly one-way, with one party authenticating the identity of another.
For example, when HTTPS is used between a web browser and a web server, the browser obtains proof of the identity of the web server.
|
SCRAM (Salted Challenge Response Authentication Mechanism) is an authentication protocol that can establish mutual authentication using passwords.
Strimzi can configure Kafka to use SASL (Simple Authentication and Security Layer) SCRAM-SHA-512 to provide authentication on both unencrypted and encrypted client connections.
When SCRAM-SHA-512 authentication is used with a TLS connection, the TLS protocol provides the encryption, but is not used for authentication.
The following properties of SCRAM make it safe to use SCRAM-SHA-512 even on unencrypted connections:
-
The passwords are not sent in the clear over the communication channel.
Instead the client and the server are each challenged by the other to offer proof that they know the password of the authenticating user.
-
The server and client each generate a new challenge for each authentication exchange.
This means that the exchange is resilient against replay attacks.
When KafkaUser.spec.authentication.type
is configured with scram-sha-512
the User Operator will generate a random 32-character password consisting of upper and lowercase ASCII letters and numbers.
Control listener access by configuring the networkPolicyPeers
property in the Kafka
resource.
By default, Strimzi automatically creates a NetworkPolicy
resource for every enabled Kafka listener, allowing connections from all namespaces.
If you want to use custom network policies, you can set the STRIMZI_NETWORK_POLICY_GENERATION
environment variable to false
in the Cluster Operator configuration.
For more information, see Configuring the Cluster Operator.
Note
|
Your configuration of Kubernetes must support ingress NetworkPolicies in order to use network policies.
|
Procedure
-
Configure the networkPolicyPeers
property to define the application pods or namespaces allowed to access the Kafka cluster.
This example shows configuration for a tls
listener to allow connections only from application pods with the label app
set to kafka-client
:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: tls
networkPolicyPeers:
- podSelector:
matchLabels:
app: kafka-client
# ...
zookeeper:
# ...
-
Apply the changes to the Kafka
resource configuration.
This procedure shows how to configure custom server certificates for TLS listeners or external listeners which have TLS encryption enabled.
By default, Kafka listeners use certificates signed by Strimzi’s internal CA (certificate authority).
The Cluster Operator automatically generates a CA certificate when creating a Kafka cluster.
To configure a client for TLS, the CA certificate is included in its truststore configuration to authenticate the Kafka cluster.
Alternatively, you have the option to install and use your own CA certificates.
However, if you prefer more granular control by using your own custom certificates at the listener-level, you can configure listeners using brokerCertChainAndKey
properties.
You create a secret with your own private key and server certificate, then specify them in the brokerCertChainAndKey
configuration.
User-provided certificates allow you to leverage existing security infrastructure.
You can use a certificate signed by a public (external) CA or a private CA.
Kafka clients need to trust the CA which was used to sign the listener certificate.
If signed by a public CA, you usually won’t need to add it to a client’s truststore configuration.
Custom certificates are not managed by Strimzi, so you need to renew them manually.
Note
|
Listener certificates are used for TLS encryption and server authentication only.
They are not used for TLS client authentication.
If you want to use your own certificate for TLS client authentication as well, you must install and use your own clients CA.
|
If you are not using a self-signed certificate, you can provide a certificate that includes the whole CA chain in the certificate.
You can only use the brokerCertChainAndKey
properties if TLS encryption (tls: true
) is configured for the listener.
Note
|
Strimzi does not support the use of encrypted private keys for TLS. The private key stored in the secret must be unencrypted for this to work.
|
Procedure
-
Create a Secret
containing your private key and server certificate:
kubectl create secret generic <my_secret> --from-file=<my_listener_key.key> --from-file=<my_listener_certificate.crt>
-
Edit the Kafka
resource for your cluster.
Configure the listener to use your Secret
, certificate file, and private key file in the configuration.brokerCertChainAndKey
property.
Example configuration for a loadbalancer
external listener with TLS encryption enabled
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: external3
port: 9094
type: loadbalancer
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-listener-certificate.crt
key: my-listener-key.key
# ...
Example configuration for a TLS listener
# ...
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: tls
port: 9093
type: internal
tls: true
configuration:
brokerCertChainAndKey:
secretName: my-secret
certificate: my-listener-certificate.crt
key: my-listener-key.key
# ...
-
Apply the changes to the Kafka
resource configuration.
The Cluster Operator starts a rolling update of the Kafka cluster, which updates the configuration of the listeners.
Note
|
A rolling update is also started if you update a Kafka listener certificate in a Secret that is already used by a listener.
|
In order to use TLS hostname verification with custom Kafka listener certificates, you must specify the correct Subject Alternative Names (SANs) for each listener.
The certificate SANs must specify hostnames for the following:
You can use wildcard certificates if they are supported by your CA.
Use the following examples to help you specify hostnames of the SANs in your certificates for your internal listeners.
Replace <cluster-name>
with the name of the Kafka cluster and <namespace>
with the Kubernetes namespace where the cluster is running.
Wildcards example for a type: internal
listener
//Kafka brokers
*.<cluster_name>-kafka-brokers
*.<cluster_name>-kafka-brokers.<namespace>.svc
// Bootstrap service
<cluster_name>-kafka-bootstrap
<cluster_name>-kafka-bootstrap.<namespace>.svc
Non-wildcards example for a type: internal
listener
// Kafka brokers
<cluster_name>-kafka-0.<cluster_name>-kafka-brokers
<cluster_name>-kafka-0.<cluster_name>-kafka-brokers.<namespace>.svc
<cluster_name>-kafka-1.<cluster_name>-kafka-brokers
<cluster_name>-kafka-1.<cluster_name>-kafka-brokers.<namespace>.svc
# ...
// Bootstrap service
<cluster_name>-kafka-bootstrap
<cluster_name>-kafka-bootstrap.<namespace>.svc
Non-wildcards example for a type: cluster-ip
listener
// Kafka brokers
<cluster_name>-kafka-<listener-name>-0
<cluster_name>-kafka-<listener-name>-0.<namespace>.svc
<cluster_name>-kafka-_listener-name>-1
<cluster_name>-kafka-<listener-name>-1.<namespace>.svc
# ...
// Bootstrap service
<cluster_name>-kafka-<listener-name>-bootstrap
<cluster_name>-kafka-<listener-name>-bootstrap.<namespace>.svc
For external listeners which have TLS encryption enabled, the hostnames you need to specify in certificates depends on the external listener type
.
Table 19. SANs for each type of external listener
External listener type |
In the SANs, specify… |
ingress
|
Addresses of all Kafka broker Ingress resources and the address of the bootstrap Ingress .
You can use a matching wildcard name. |
route
|
Addresses of all Kafka broker Routes and the address of the bootstrap Route .
You can use a matching wildcard name. |
loadbalancer
|
Addresses of all Kafka broker loadbalancers and the bootstrap loadbalancer address.
You can use a matching wildcard name. |
nodeport
|
Addresses of all Kubernetes worker nodes that the Kafka broker pods might be scheduled to.
You can use a matching wildcard name. |
Configure authorized access to a Kafka cluster using the Kafka.spec.kafka.authorization
property in the Kafka
resource.
If the authorization
property is missing, no authorization is enabled and clients have no restrictions.
When enabled, authorization is applied to all enabled listeners.
The authorization method is defined in the type
field.
Supported authorization options:
Figure 5. Kafka cluster authorization options
Super users can access all resources in your Kafka cluster regardless of any access restrictions,
and are supported by all authorization mechanisms.
To designate super users for a Kafka cluster, add a list of user principals to the superUsers
property.
If a user uses mTLS authentication, the username is the common name from the TLS certificate subject prefixed with CN=
.
If you are not using the User Operator and using your own certificates for mTLS, the username is the full certificate subject.
A full certificate subject can include the following fields:
-
CN=<common_name>
-
OU=<organizational_unit>
-
O=<organization>
-
L=<locality>
-
ST=<state>
-
C=<country_code>
Omit any fields that are not applicable.
An example configuration with super users
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
authorization:
type: simple
superUsers:
- CN=user-1
- user-2
- CN=user-3
- CN=user-4,OU=my-ou,O=my-org,L=my-location,ST=my-state,C=US
- CN=user-5,OU=my-ou,O=my-org,C=GB
- CN=user-6,O=my-org
# ...
When configuring security mechanisms in clients, the clients are represented as users.
Use the KafkaUser
resource to configure the authentication, authorization, and access rights for Kafka clients.
Authentication permits user access, and authorization constrains user access to permissible actions.
You can also create super users that have unconstrained access to Kafka brokers.
A KafkaUser
resource includes a label that defines the appropriate name of the Kafka cluster (derived from the name of the Kafka
resource) to which it belongs.
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
The label enables the User Operator to identify the KafkaUser
resource and create and manager the user.
If the label does not match the Kafka cluster, the User Operator cannot identify the KafkaUser
, and the user is not created.
If the status of the KafkaUser
resource remains empty, check your label configuration.
Use the KafkaUser
custom resource to configure authentication credentials for users (clients) that require access to a Kafka cluster.
Configure the credentials using the authentication
property in KafkaUser.spec
.
By specifying a type
, you control what credentials are generated.
Supported authentication types:
-
tls
for mTLS authentication
-
tls-external
for mTLS authentication using external certificates
-
scram-sha-512
for SCRAM-SHA-512 authentication
If tls
or scram-sha-512
is specified, the User Operator creates authentication credentials when it creates the user.
If tls-external
is specified, the user still uses mTLS, but no authentication credentials are created.
Use this option when you’re providing your own certificates.
When no authentication type is specified, the User Operator does not create the user or its credentials.
You can use tls-external
to authenticate with mTLS using a certificate issued outside the User Operator.
The User Operator does not generate a TLS certificate or a secret.
You can still manage ACL rules and quotas through the User Operator in the same way as when you’re using the tls
mechanism.
This means that you use the CN=USER-NAME
format when specifying ACL rules and quotas.
USER-NAME is the common name given in a TLS certificate.
To use mTLS authentication, you set the type
field in the KafkaUser
resource to tls
.
Example user with mTLS authentication enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: tls
# ...
The authentication type must match the equivalent configuration for the Kafka
listener used to access the Kafka cluster.
When the user is created by the User Operator, it creates a new secret with the same name as the KafkaUser
resource.
The secret contains a private and public key for mTLS.
The public key is contained in a user certificate, which is signed by a clients CA (certificate authority) when it is created.
All keys are in X.509 format.
Note
|
If you are using the clients CA generated by the Cluster Operator, the user certificates generated by the User Operator are also renewed when the clients CA is renewed by the Cluster Operator.
|
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
When you configure a client, you specify the following:
The configuration depends on the file format (PEM or PKCS #12).
This example uses PKCS #12 stores, and the passwords required to access the credentials in the stores.
Example client configuration using mTLS in PKCS #12 format
bootstrap.servers=<kafka_cluster_name>-kafka-bootstrap:9093 # (1)
security.protocol=SSL # (2)
ssl.truststore.location=/tmp/ca.p12 # (3)
ssl.truststore.password=<truststore_password> # (4)
ssl.keystore.location=/tmp/user.p12 # (5)
ssl.keystore.password=<keystore_password> # (6)
-
The bootstrap server address to connect to the Kafka cluster.
-
The security protocol option when using TLS for encryption.
-
The truststore location contains the public key certificate (ca.p12
) for the Kafka cluster. A cluster CA certificate and password is generated by the Cluster Operator in the <cluster_name>-cluster-ca-cert
secret when the Kafka cluster is created.
-
The password (ca.password
) for accessing the truststore.
-
The keystore location contains the public key certificate (user.p12
) for the Kafka user.
-
The password (user.password
) for accessing the keystore.
To use mTLS authentication using a certificate issued outside the User Operator, you set the type
field in the KafkaUser
resource to tls-external
.
A secret and credentials are not created for the user.
Example user with mTLS authentication that uses a certificate issued outside the User Operator
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: tls-external
# ...
To use the SCRAM-SHA-512 authentication mechanism, you set the type
field in the KafkaUser
resource to scram-sha-512
.
Example user with SCRAM-SHA-512 authentication enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: scram-sha-512
# ...
When the user is created by the User Operator, it creates a new secret with the same name as the KafkaUser
resource.
The secret contains the generated password in the password
key, which is encoded with base64.
In order to use the password, it must be decoded.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
password: Z2VuZXJhdGVkcGFzc3dvcmQ= (1)
sasl.jaas.config: b3JnLmFwYWNoZS5rYWZrYS5jb21tb24uc2VjdXJpdHkuc2NyYW0uU2NyYW1Mb2dpbk1vZHVsZSByZXF1aXJlZCB1c2VybmFtZT0ibXktdXNlciIgcGFzc3dvcmQ9ImdlbmVyYXRlZHBhc3N3b3JkIjsK (2)
-
The generated password, base64 encoded.
-
The JAAS configuration string for SASL SCRAM-SHA-512 authentication, base64 encoded.
Decoding the generated password:
echo "Z2VuZXJhdGVkcGFzc3dvcmQ=" | base64 --decode
When a user is created, Strimzi generates a random password.
You can use your own password instead of the one generated by Strimzi. To do so, create a secret with the password and reference it in the KafkaUser
resource.
Example user with a password set for SCRAM-SHA-512 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication:
type: scram-sha-512
password:
valueFrom:
secretKeyRef:
name: my-secret # (1)
key: my-password # (2)
# ...
-
The name of the secret containing the predefined password.
-
The key for the password stored inside the secret.
Use the KafkaUser
custom resource to configure authorization rules for users (clients) that require access to a Kafka cluster.
Configure the rules using the authorization
property in KafkaUser.spec
.
By specifying a type
, you control what rules are used.
To use simple authorization, you set the type
property to simple
in KafkaUser.spec.authorization
.
The simple authorization uses the Kafka Admin API to manage the ACL rules inside your Kafka cluster.
Whether ACL management in the User Operator is enabled or not depends on your authorization configuration in the Kafka cluster.
-
For simple authorization, ACL management is always enabled.
-
For OPA authorization, ACL management is always disabled.
Authorization rules are configured in the OPA server.
-
For Keycloak authorization, you can manage the ACL rules directly in Keycloak.
You can also delegate authorization to the simple authorizer as a fallback option in the configuration.
When delegation to the simple authorizer is enabled, the User Operator will enable management of ACL rules as well.
-
For custom authorization using a custom authorization plugin, use the supportsAdminApi
property in the .spec.kafka.authorization
configuration of the Kafka
custom resource to enable or disable the support.
Authorization is cluster-wide.
The authorization type must match the equivalent configuration in the Kafka
custom resource.
If ACL management is not enabled, Strimzi rejects a resource if it contains any ACL rules.
If you’re using a standalone deployment of the User Operator, ACL management is enabled by default.
You can disable it using the STRIMZI_ACLS_ADMIN_API_SUPPORTED
environment variable.
If no authorization is specified, the User Operator does not provision any access rights for the user.
Whether such a KafkaUser
can still access resources depends on the authorizer being used.
For example, for simple
authorization, this is determined by the allow.everyone.if.no.acl.found
configuration in the Kafka cluster.
simple
authorization uses ACL rules to manage access to Kafka brokers.
ACL rules grant access rights to the user, which you specify in the acls
property.
If a user is added to a list of super users in a Kafka broker configuration,
the user is allowed unlimited access to the cluster regardless of any authorization constraints defined in ACLs in KafkaUser
.
Configure the spec
for the KafkaUser
resource to enforce quotas so that a user does not overload Kafka brokers.
Set size-based network usage and time-based CPU utilization thresholds.
Partition mutations occur in response to the following types of user requests:
-
Creating partitions for a new topic
-
Adding partitions to an existing topic
-
Deleting partitions from a topic
You can also add a partition mutation quota to control the rate at which requests to change partitions are accepted.
Example KafkaUser
with user quotas
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
# ...
quotas:
producerByteRate: 1048576 # (1)
consumerByteRate: 2097152 # (2)
requestPercentage: 55 # (3)
controllerMutationRate: 10 # (4)
-
Byte-per-second quota on the amount of data the user can push to a Kafka broker.
-
Byte-per-second quota on the amount of data the user can fetch from a Kafka broker.
-
CPU utilization limit as a percentage of time for a client group.
-
Number of concurrent partition creation and deletion operations (mutations) allowed per second.
Using quotas for Kafka clients might be useful in a number of situations.
Consider a wrongly configured Kafka producer which is sending requests at too high a rate.
Such misconfiguration can cause a denial of service to other clients, so the problematic client ought to be blocked.
By using a network limiting quota, it is possible to prevent this situation from significantly impacting other clients.
Note
|
Strimzi supports user-level quotas, but not client-level quotas.
|
This procedure shows how to configure client access to a Kafka cluster from outside Kubernetes or from another Kubernetes cluster.
It’s split into two parts:
Resource configuration
Client access to the Kafka cluster is secured with the following configuration:
-
An external listener is configured with TLS encryption and mutual TLS (mTLS) authentication in the Kafka
resource, as well as simple
authorization.
-
A KafkaUser
is created for the client, utilizing mTLS authentication, and Access Control Lists (ACLs) are defined for simple
authorization.
At least one listener supporting the desired authentication must be configured for the KafkaUser
.
Listeners can be configured for mutual TLS
, SCRAM-SHA-512
, or OAuth
authentication.
While mTLS always uses encryption, it’s also recommended when using SCRAM-SHA-512 and OAuth 2.0 authentication.
Authorization options for Kafka include simple
, OAuth
, OPA
, or custom
.
When enabled, authorization is applied to all enabled listeners.
To ensure compatibility between Kafka and clients, configuration of the following authentication and authorization mechanisms must align:
-
For type: tls
and type: scram-sha-512
authentication types, Kafka.spec.kafka.listeners[*].authentication
must match KafkaUser.spec.authentication
-
For type: simple
authorization,Kafka.spec.kafka.authorization
must match KafkaUser.spec.authorization
For example, mTLS authentication for a user is only possible if it’s also enabled in the Kafka configuration.
Automation and certificate management
Strimzi operators automate the configuration process and create the certificates required for authentication:
-
The Cluster Operator creates the listeners and sets up the cluster and client certificate authority (CA) certificates to enable authentication within the Kafka cluster.
-
The User Operator creates the user representing the client and the security credentials used for client authentication, based on the chosen authentication type.
You add the certificates to your client configuration.
Certificates are available in PEM (.crt) and PKCS #12 (.p12) formats.
This procedure uses PEM certificates.
Use PEM certificates with clients that support the X.509 certificate format.
-
Configure the Kafka cluster with a Kafka listener.
-
Apply the changes to the Kafka
resource configuration.
The Kafka cluster is configured with a Kafka broker listener using mTLS authentication.
A service is created for each Kafka broker pod.
A service is created to serve as the bootstrap address for connection to the Kafka cluster.
A service is also created as the external bootstrap address for external connection to the Kafka cluster using nodeport
listeners.
The cluster CA certificate to verify the identity of the kafka brokers is also created in the secret <cluster_name>-cluster-ca-cert
.
Note
|
If you scale your Kafka cluster while using external listeners, it might trigger a rolling update of all Kafka brokers. This depends on the configuration.
|
-
Retrieve the bootstrap address you can use to access the Kafka cluster from the status of the Kafka
resource.
kubectl get kafka <kafka_cluster_name> -o=jsonpath='{.status.listeners[?(@.name=="<listener_name>")].bootstrapServers}{"\n"}'
kubectl get kafka my-cluster -o=jsonpath='{.status.listeners[?(@.name=="external")].bootstrapServers}{"\n"}'
Use the bootstrap address in your Kafka client to connect to the Kafka cluster.
-
Create or modify a user representing the client that requires access to the Kafka cluster.
-
Apply the changes to the KafkaUser
resource configuration.
The user is created, as well as a secret with the same name as the KafkaUser
resource.
The secret contains a public and private key for mTLS authentication.
Example secret with user credentials
apiVersion: v1
kind: Secret
metadata:
name: my-user
labels:
strimzi.io/kind: KafkaUser
strimzi.io/cluster: my-cluster
type: Opaque
data:
ca.crt: <public_key> # Public key of the clients CA used to sign this user certificate
user.crt: <user_certificate> # Public key of the user
user.key: <user_private_key> # Private key of the user
user.p12: <store> # PKCS #12 store for user certificates and keys
user.password: <password_for_store> # Protects the PKCS #12 store
-
Extract the cluster CA certificate from the <cluster_name>-cluster-ca-cert
secret of the Kafka cluster.
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Extract the user CA certificate from the <user_name>
secret.
kubectl get secret <user_name> -o jsonpath='{.data.user\.crt}' | base64 -d > user.crt
-
Extract the private key of the user from the <user_name>
secret.
kubectl get secret <user_name> -o jsonpath='{.data.user\.key}' | base64 -d > user.key
-
Configure your client with the bootstrap address hostname and port for connecting to the Kafka cluster:
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "<hostname>:<port>");
-
Configure your client with the truststore credentials to verify the identity of the Kafka cluster.
Specify the public cluster CA certificate.
Example truststore configuration
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PEM");
props.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, "<ca.crt_file_content>");
SSL is the specified security protocol for mTLS authentication.
Specify SASL_SSL
for SCRAM-SHA-512 authentication over TLS.
PEM is the file format of the truststore.
-
Configure your client with the keystore credentials to verify the user when connecting to the Kafka cluster.
Specify the public certificate and private key.
Example keystore configuration
props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
props.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PEM");
props.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, "<user.crt_file_content>");
props.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, "<user.key_file_content>");
Add the keystore certificate and the private key directly to the configuration.
Add as a single-line format.
Between the BEGIN CERTIFICATE
and END CERTIFICATE
delimiters, start with a newline character (\n
).
End each line from the original certificate with \n
too.
Example keystore configuration
props.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, "-----BEGIN CERTIFICATE----- \n<user_certificate_content_line_1>\n<user_certificate_content_line_n>\n-----END CERTIFICATE---");
props.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, "----BEGIN PRIVATE KEY-----\n<user_key_content_line_1>\n<user_key_content_line_n>\n-----END PRIVATE KEY-----");
Off-cluster access using node ports with TLS encryption enabled does not support TLS hostname verification.
Consequently, clients that perform hostname verification will fail to connect.
For example, a Java client will fail with the following exception:
Exception for TLS hostname verification
Caused by: java.security.cert.CertificateException: No subject alternative names matching IP address 168.72.15.231 found
...
To connect, you must disable hostname verification.
In the Java client, set the ssl.endpoint.identification.algorithm
configuration option to an empty string.
When configuring the client using a properties file, you can do it this way:
ssl.endpoint.identification.algorithm=
When configuring the client directly in Java, set the configuration option to an empty string:
props.put("ssl.endpoint.identification.algorithm", "");
Strimzi supports OAuth 2.0 for securing Kafka clusters by integrating with an OAUth 2.0 authorization server.
Kafka brokers and clients both need to be configured to use OAuth 2.0.
OAuth 2.0 enables standardized token-based authentication and authorization between applications, using a central authorization server to issue tokens that grant limited access to resources.
You can define specific scopes for fine-grained access control.
Scopes correspond to different levels of access to Kafka topics or operations within the cluster.
OAuth 2.0 also supports single sign-on and integration with identity providers.
Before you can use OAuth 2.0 token-based access, you must configure an authorization server for integration with Strimzi.
The steps are dependent on the chosen authorization server.
Consult the product documentation for the authorization server for information on how to set up OAuth 2.0 access.
Prepare the authorization server to work with Strimzi by defining OAUth 2.0 clients for Kafka and each Kafka client component of your application.
In relation to the authorization server, the Kafka cluster and Kafka clients are both regarded as OAuth 2.0 clients.
In general, configure OAuth 2.0 clients in the authorization server with the following client credentials enabled:
-
Client ID (for example, kafka
for the Kafka cluster)
-
Client ID and secret as the authentication mechanism
Note
|
You only need to use a client ID and secret when using a non-public introspection endpoint of the authorization server.
The credentials are not typically required when using public authorization server endpoints, as with fast local JWT token validation.
|
Strimzi supports the use of OAuth 2.0 for token-based authentication.
An OAuth 2.0 authorization server handles the granting of access and inquiries about access.
Kafka clients authenticate to Kafka brokers.
Brokers and clients communicate with the authorization server, as necessary, to obtain or validate access tokens.
For a deployment of Strimzi, OAuth 2.0 integration provides the following support:
-
Server-side OAuth 2.0 authentication for Kafka brokers
-
Client-side OAuth 2.0 authentication for Kafka MirrorMaker, Kafka Connect, and the Kafka Bridge
To secure Kafka brokers with OAuth 2.0 authentication, configure a listener in the Kafka
resource to use OAUth 2.0 authentication and a client authentication mechanism, and add further configuration depending on the authentication mechanism and type of token validation used in the authentication.
Configuring listeners to use oauth
authentication
Specify a listener in the Kafka
resource with an oauth
authentication type.
You can configure internal and external listeners.
We recommend using OAuth 2.0 authentication together with TLS encryption (tls: true
).
Without encryption, the connection is vulnerable to network eavesdropping and unauthorized access through token theft.
Example listener configuration with OAuth 2.0 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
#...
Enabling SASL authentication mechanisms
Use one or both of the following SASL mechanisms for clients to exchange credentials and establish authenticated sessions with Kafka.
OAUTHBEARER
-
Using the OAUTHBEARER
authentication mechanism, credentials exchange uses a bearer token provided by an OAuth callback handler.
Token provision can be configured to use the following methods:
-
Client ID and secret (using the OAuth 2.0 client credentials mechanism)
-
Client ID and client assertion
-
Long-lived access token or Service account token
-
Long-lived refresh token obtained manually
OAUTHBEARER
is recommended as it provides a higher level of security than PLAIN
, though it can only be used by Kafka clients that support the OAUTHBEARER
mechanism at the protocol level.
Client credentials are never shared with Kafka.
PLAIN
-
PLAIN
is a simple authentication mechanism used by all Kafka client tools.
Consider using PLAIN
only with Kafka clients that do not support OAUTHBEARER
.
Using the PLAIN
authentication mechanism, credentials exchange can be configured to use the following methods:
-
Client ID and secret (using the OAuth 2.0 client credentials mechanism)
-
Long-lived access token
Regardless of the method used, the client must provide username
and password
properties to Kafka.
Credentials are handled centrally behind a compliant authorization server, similar to how OAUTHBEARER
authentication is used.
The username extraction process depends on the authorization server configuration.
OAUTHBEARER
is automatically enabled in the oauth
listener configuration for the Kafka broker.
To use the PLAIN
mechanism, you must set the enablePlain
property to true
.
In the following example, the PLAIN
mechanism is enabled, and the OAUTHBEARER
mechanism is disabled on a listener using the enableOauthBearer
property.
Example listener configuration for the PLAIN
mechanism
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
enablePlain: true
enableOauthBearer: false
#...
When you have defined the type of authentication as OAuth 2.0, you add configuration based on the type of validation, either as fast local JWT validation or token validation using an introspection endpoint.
Configuring fast local JWT token validation
Fast local JWT token validation involves checking a JWT token signature locally to ensure that the token meets the following criteria:
-
Contains a typ
(type) or token_type
header claim value of Bearer
to indicate it is an access token
-
Is currently valid and not expired
-
Has an issuer that matches a validIssuerURI
You specify a validIssuerURI
attribute when you configure the listener, so that any tokens not issued by the authorization server are rejected.
The authorization server does not need to be contacted during fast local JWT token validation.
You activate fast local JWT token validation by specifying a jwksEndpointUri
attribute, the endpoint exposed by the OAuth 2.0 authorization server.
The endpoint contains the public keys used to validate signed JWT tokens, which are sent as credentials by Kafka clients.
All communication with the authorization server should be performed using TLS encryption.
You can configure a certificate truststore as a Kubernetes Secret
in your Strimzi project namespace, and use the tlsTrustedCertificates
property to point to the Kubernetes secret containing the truststore file.
You might want to configure a userNameClaim
to properly extract a username from the JWT token.
If required, you can use a JsonPath expression like "['user.info'].['user.id']"
to retrieve the username from nested JSON attributes within a token.
If you want to use Kafka ACL authorization, identify the user by their username during authentication. (The sub
claim in JWT tokens is typically a unique ID, not a username.)
Example configuration for fast local JWT token validation
#...
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth # (1)
validIssuerUri: https://<auth_server_address>/<issuer-context> # (2)
jwksEndpointUri: https://<auth_server_address>/<path_to_jwks_endpoint> # (3)
userNameClaim: preferred_username # (4)
maxSecondsWithoutReauthentication: 3600 # (5)
tlsTrustedCertificates: # (6)
- secretName: oauth-server-cert
pattern: "*.crt"
disableTlsHostnameVerification: true # (7)
jwksExpirySeconds: 360 # (8)
jwksRefreshSeconds: 300 # (9)
jwksMinRefreshPauseSeconds: 1 # (10)
-
Listener type set to oauth
.
-
URI of the token issuer used for authentication.
-
URI of the JWKS certificate endpoint used for local JWT validation.
-
The token claim (or key) that contains the actual username used to identify the user. Its value depends on the authorization server. If necessary, a JsonPath expression like "['user.info'].['user.id']"
can be used to retrieve the username from nested JSON attributes within a token.
-
(Optional) Activates the Kafka re-authentication mechanism that enforces session expiry to the same length of time as the access token. If the specified value is less than the time left for the access token to expire, then the client will have to re-authenticate before the actual token expiry. By default, the session does not expire when the access token expires, and the client does not attempt re-authentication.
-
(Optional) Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
-
(Optional) Disable TLS hostname verification. Default is false
.
-
The duration the JWKS certificates are considered valid before they expire. Default is 360
seconds. If you specify a longer time, consider the risk of allowing access to revoked certificates.
-
The period between refreshes of JWKS certificates. The interval must be at least 60 seconds shorter than the expiry interval. Default is 300
seconds.
-
The minimum pause in seconds between consecutive attempts to refresh JWKS public keys. When an unknown signing key is encountered, the JWKS keys refresh is scheduled outside the regular periodic schedule with at least the specified pause since the last refresh attempt. The refreshing of keys follows the rule of exponential backoff, retrying on unsuccessful refreshes with ever increasing pause, until it reaches jwksRefreshSeconds
. The default value is 1.
Configuring fast local JWT token validation with Kubernetes service accounts
To configure the listener for Kubernetes service accounts, the Kubernetes API server must be used as the authorization server.
Example configuration for fast local JWT token validation using Kubernetes API server as authorization server
#...
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
validIssuerUri: https://kubernetes.default.svc.cluster.local # (1)
jwksEndpointUri: https://kubernetes.default.svc.cluster.local/openid/v1/jwks # (2)
serverBearerTokenLocation: /var/run/secrets/kubernetes.io/serviceaccount/token # (3)
checkAccessTokenType: false # (4)
includeAcceptHeader: false # (5)
tlsTrustedCertificates: # (6)
- secretName: oauth-server-cert
pattern: "*.crt"
maxSecondsWithoutReauthentication: 3600
customClaimCheck: "@.['kubernetes.io'] && @.['kubernetes.io'].['namespace'] in ['myproject']" # (7)
-
URI of the token issuer used for authentication. Must use FQDN, including the .cluster.local
extension, which may vary based on the Kubernetes cluster configuration.
-
URI of the JWKS certificate endpoint used for local JWT validation. Must use FQDN, including the .cluster.local
extension, which may vary based on the Kubernetes cluster configuration.
-
Location to the access token used by the Kafka broker to authenticate to the Kubernetes API server in order to access the jwksEndpointUri
.
-
Skip the access token type check, as the claim for this is not present in service account tokens.
-
Skip sending Accept
header in HTTP requests to the JWKS endpoint, as the Kubernetes API server does not support it.
-
Trusted certificates to connect to authorization server. This should point to a manually created Secret that contains the Kubernetes API server public certificate, which is mounted to the running pods under /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
. You can use the following command to create the Secret:
kubectl get cm kube-root-ca.crt -o jsonpath="{['data']['ca\.crt']}" > /tmp/ca.crt
kubectl create secret generic oauth-server-cert --from-file=ca.crt=/tmp/ca.crt
-
(Optional) Additional constraints that JWT token has to fulfill in order to be accepted, expressed as JsonPath filter query. In this example the service account has to belong to myproject
namespace in order to be allowed to authenticate.
The above configuration uses the sub
claim from the service account JWT token as the user ID. For example, the default service account for pods deployed in the myproject
namespace has the username: system:serviceaccount:myproject:default
.
When configuring ACLs the general form of how to refer to the ServiceAccount user should in that case be: User:system:serviceaccount:<Namespace>:<ServiceAccount-name>
Configuring token validation using an introspection endpoint
Token validation using an OAuth 2.0 introspection endpoint treats a received access token as opaque. The Kafka broker sends an access token to the introspection endpoint, which responds with the token information necessary for validation.
Importantly, it returns up-to-date information if the specific access token is valid, and also information about when the token expires.
To configure OAuth 2.0 introspection-based validation, you specify an introspectionEndpointUri attribute rather than the jwksEndpointUri
attribute specified for fast local JWT token validation.
Depending on the authorization server, you typically have to specify a clientId
and clientSecret
, because the introspection endpoint is usually protected.
Example token validation configuration using an introspection endpoint
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
validIssuerUri: https://<auth_server_address>/<issuer-context>
introspectionEndpointUri: https://<auth_server_address>/<path_to_introspection_endpoint> # (1)
clientId: kafka-broker # (2)
clientSecret: # (3)
secretName: my-cluster-oauth
key: clientSecret
userNameClaim: preferred_username # (4)
maxSecondsWithoutReauthentication: 3600 # (5)
tlsTrustedCertificates:
- secretName: oauth-server-cert
pattern: "*.crt"
-
URI of the token introspection endpoint.
-
Client ID to identify the client.
-
Client Secret and client ID is used for authentication.
-
The token claim (or key) that contains the actual username used to identify the user. Its value depends on the authorization server. If necessary, a JsonPath expression like "['user.info'].['user.id']"
can be used to retrieve the username from nested JSON attributes within a token.
-
(Optional) Activates the Kafka re-authentication mechanism that enforces session expiry to the same length of time as the access token. If the specified value is less than the time left for the access token to expire, then the client will have to re-authenticate before the actual token expiry. By default, the session does not expire when the access token expires, and the client does not attempt re-authentication.
Authenticating brokers to the authorization server protected endpoints
Usually, the certificates endpoint of the authorization server (jwksEndpointUri
) is publicly accessible, while the introspection endpoint (introspectionEndpointUri
) is protected.
However, this may vary depending on the authorization server configuration.
The Kafka broker can authenticate to the authorization server’s protected endpoints in one of two ways using HTTP authentication schemes:
To configure HTTP Basic authentication, set the following properties:
For HTTP Bearer authentication, set the following property:
Including additional configuration options
Specify additional settings depending on the authentication requirements and the authorization server you are using.
Some of these properties apply only to certain authentication mechanisms or when used in combination with other properties.
For example, when using OAUth over PLAIN
, access tokens are passed as password
property values with or without an $accessToken:
prefix.
-
If you configure a token endpoint (tokenEndpointUri
) in the listener configuration, you need the prefix.
-
If you don’t configure a token endpoint in the listener configuration, you don’t need the prefix.
The Kafka broker interprets the password as a raw access token.
If the password
is set as the access token, the username
must be set to the same principal name that the Kafka broker obtains from the access token.
You can specify username extraction options in your listener using the userNameClaim
, usernamePrefix
, fallbackUserNameClaim
, fallbackUsernamePrefix
, and userInfoEndpointUri
properties.
The username extraction process also depends on your authorization server; in particular, how it maps client IDs to account names.
Note
|
The PLAIN mechanism does not support password grant authentication.
Use either client credentials (client ID + secret) or an access token for authentication.
|
Example optional configuration settings
# ...
authentication:
type: oauth
# ...
checkIssuer: false # (1)
checkAudience: true # (2)
usernamePrefix: user- # (3)
fallbackUserNameClaim: client_id # (4)
fallbackUserNamePrefix: client-account- # (5)
serverBearerTokenLocation: path/to/access/token # (6)
validTokenType: bearer # (7)
userInfoEndpointUri: https://<auth_server_address>/<path_to_userinfo_endpoint> # (8)
enableOauthBearer: false # (9)
enablePlain: true # (10)
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint> # (11)
customClaimCheck: "@.custom == 'custom-value'" # (12)
clientAudience: audience # (13)
clientScope: scope # (14)
connectTimeoutSeconds: 60 # (15)
readTimeoutSeconds: 60 # (16)
httpRetries: 2 # (17)
httpRetryPauseMs: 300 # (18)
groupsClaim: "$.groups" # (19)
groupsClaimDelimiter: "," # (20)
includeAcceptHeader: false # (21)
-
If your authorization server does not provide an iss
claim, it is not possible to perform an issuer check. In this situation, set checkIssuer
to false
and do not specify a validIssuerUri
. Default is true
.
-
If your authorization server provides an aud
(audience) claim, and you want to enforce an audience check, set checkAudience
to true
. Audience checks identify the intended recipients of tokens. As a result, the Kafka broker will reject tokens that do not have its clientId
in their aud
claim. Default is false
.
-
The prefix used when constructing the user ID. This only takes effect if userNameClaim
is configured.
-
An authorization server may not provide a single attribute to identify both regular users and clients. When a client authenticates in its own name, the server might provide a client ID. When a user authenticates using a username and password to obtain a refresh token or an access token, the server might provide a username attribute in addition to a client ID. Use this fallback option to specify the username claim (attribute) to use if a primary user ID attribute is not available. If necessary, a JsonPath expression like "['client.info'].['client.id']"
can be used to retrieve the fallback username to retrieve the username from nested JSON attributes within a token.
-
In situations where fallbackUserNameClaim
is applicable, it may also be necessary to prevent name collisions between the values of the username claim, and those of the fallback username claim. Consider a situation where a client called producer
exists, but also a regular user called producer
exists. In order to differentiate between the two, you can use this property to add a prefix to the user ID of the client.
-
The location of the access token used by the Kafka broker to authenticate to the Kubernetes API server for accessing protected endpoints. The authorization server must support OAUTHBEARER
authentication. This is an alternative to specifying clientId
and clientSecret
, which uses PLAIN
authentication.
-
(Only applicable when using introspectionEndpointUri
) Depending on the authorization server you are using, the introspection endpoint may or may not return the token type attribute, or it may contain different values. You can specify a valid token type value that the response from the introspection endpoint has to contain.
-
(Only applicable when using introspectionEndpointUri
) The authorization server may be configured or implemented in such a way to not provide any identifiable information in an introspection endpoint response. In order to obtain the user ID, you can configure the URI of the userinfo
endpoint as a fallback. The userNameClaim
, fallbackUserNameClaim
, and fallbackUserNamePrefix
settings are applied to the response of userinfo
endpoint.
-
Set this to false
to disable the OAUTHBEARER
mechanism on the listener. At least one of PLAIN
or OAUTHBEARER
has to be enabled. Default is true
.
-
Set to true
to enable PLAIN
authentication on the listener, which is supported for clients on all platforms.
-
Additional configuration for the PLAIN
mechanism. If specified, clients can authenticate over PLAIN
by passing an access token as the password
using an $accessToken:
prefix.
For production, always use https://
urls.
-
Additional custom rules can be imposed on the JWT access token during validation by setting this to a JsonPath filter query. If the access token does not contain the necessary data, it is rejected. When using the introspectionEndpointUri
, the custom check is applied to the introspection endpoint response JSON.
-
An audience
parameter passed to the token endpoint. An audience is used when obtaining an access token for inter-broker authentication. It is also used in the name of a client for OAuth 2.0 over PLAIN
client authentication using a clientId
and secret
. This only affects the ability to obtain the token, and the content of the token, depending on the authorization server. It does not affect token validation rules by the listener.
-
A scope
parameter passed to the token endpoint. A scope is used when obtaining an access token for inter-broker authentication. It is also used in the name of a client for OAuth 2.0 over PLAIN
client authentication using a clientId
and secret
. This only affects the ability to obtain the token, and the content of the token, depending on the authorization server. It does not affect token validation rules by the listener.
-
The connect timeout in seconds when connecting to the authorization server. The default value is 60.
-
The read timeout in seconds when connecting to the authorization server. The default value is 60.
-
The maximum number of times to retry a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make the Kafka broker unresponsive.
-
The time to wait before attempting another retry of a failed HTTP request to the authorization server. By default, this time is set to zero, meaning that no pause is applied. This is because many issues that cause failed requests are per-request network glitches or proxy issues that can be resolved quickly. However, if your authorization server is under stress or experiencing high traffic, you may want to set this option to a value of 100 ms or more to reduce the load on the server and increase the likelihood of successful retries.
-
A JsonPath query that is used to extract groups information from either the JWT token or the introspection endpoint response. This option is not set by default. By configuring this option, a custom authorizer can make authorization decisions based on user groups.
-
A delimiter used to parse groups information when it is returned as a single delimited string. The default value is ',' (comma).
-
Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
To configure OAuth 2.0 on client applications, you must specify the following:
-
SASL (Simple Authentication and Security Layer) security protocols
-
SASL mechanisms
-
A JAAS (Java Authentication and Authorization Service) module
-
Authentication properties to access the authorization server
Configuring SASL protocols
Specify SASL protocols in the client configuration:
Use SASL_SSL
for production and SASL_PLAINTEXT
for local development only.
When using SASL_SSL
, additional ssl.truststore
configuration is needed.
The truststore configuration is required for secure connection (https://
) to the OAuth 2.0 authorization server.
To verify the OAuth 2.0 authorization server, add the CA certificate for the authorization server to the truststore in your client configuration.
You can configure a truststore in PEM or PKCS #12 format.
Configuring SASL authentication mechanisms
Specify SASL mechanisms in the client configuration:
Configuring a JAAS module
Specify a JAAS module that implements the SASL authentication mechanism as a sasl.jaas.config
property value:
Note
|
For the OAUTHBEARER mechanism, Strimzi provides a callback handler for clients that use Kafka Client Java libraries to enable credentials exchange.
For clients in other languages, custom code may be required to obtain the access token.
For the PLAIN mechanism, Strimzi provides server-side callbacks to enable credentials exchange.
|
To be able to use the OAUTHBEARER
mechanism, you must also add the custom io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
class as the callback handler.
JaasClientOauthLoginCallbackHandler
handles OAuth callbacks to the authorization server for access tokens during client login.
This enables automatic token renewal, ensuring continuous authentication without user intervention.
Additionally, it handles login credentials for clients using the OAuth 2.0 password grant method.
Configuring authentication properties
Configure the client to use credentials or access tokens for OAuth 2.0 authentication.
- Using client credentials
-
Using client credentials involves configuring the client with the necessary credentials (client ID and secret, or client ID and client assertion) to obtain a valid access token from an authorization server. This is the simplest mechanism.
- Using access tokens
-
Using access tokens, the client is configured with a valid long-lived access token or refresh token obtained from an authorization server.
Using access tokens adds more complexity because there is an additional dependency on authorization server tools.
If you are using long-lived access tokens, you may need to configure the client in the authorization server to increase the maximum lifetime of the token.
The only information ever sent to Kafka is the access token.
The credentials used to obtain the token are never sent to Kafka.
When a client obtains an access token, no further communication with the authorization server is needed.
SASL authentication properties support the following authentication methods:
-
OAuth 2.0 client credentials
-
Access token or Service account token
-
Refresh token
-
OAuth 2.0 password grant (deprecated)
Add the authentication properties as JAAS configuration (sasl.jaas.config
and sasl.login.callback.handler.class
).
If the client application is not configured with an access token directly, the client exchanges one of the following sets of credentials for an access token during Kafka session initiation:
-
Client ID and secret
-
Client ID and client assertion
-
Client ID, refresh token, and (optionally) a secret
-
Username and password, with client ID and (optionally) a secret
Note
|
You can also specify authentication properties as environment variables, or as Java system properties.
For Java system properties, you can set them using setProperty and pass them on the command line using the -D option.
|
Example client credentials configuration using the client secret
security.protocol=SASL_SSL # (1)
sasl.mechanism=OAUTHBEARER # (2)
ssl.truststore.location=/tmp/truststore.p12 (3)
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \ # (4)
oauth.client.id="<client_id>" \ # (5)
oauth.client.secret="<client_secret>" \ # (6)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \ (7)
oauth.ssl.truststore.password="$STOREPASS" \ (8)
oauth.ssl.truststore.type="PKCS12" \ (9)
oauth.scope="<scope>" \ # (10)
oauth.audience="<audience>" ; # (11)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
SASL_SSL
security protocol for TLS-encrypted connections. Use SASL_PLAINTEXT
over unencrypted connections for local development only.
-
The SASL mechanism specified as OAUTHBEARER
or PLAIN
.
-
The truststore configuration for secure access to the Kafka cluster.
-
URI of the authorization server token endpoint.
-
Client ID, which is the name used when creating the client in the authorization server.
-
Client secret created when creating the client in the authorization server.
-
The location contains the public key certificate (truststore.p12
) for the authorization server.
-
The password for accessing the truststore.
-
The truststore type.
-
(Optional) The scope
for requesting the token from the token endpoint.
An authorization server may require a client to specify the scope.
-
(Optional) The audience
for requesting the token from the token endpoint.
An authorization server may require a client to specify the audience.
Example client credentials configuration using the client assertion
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \
oauth.client.assertion.location="<path_to_client_assertion_token_file>" \ # (1)
oauth.client.assertion.type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer" \ # (2)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.scope="<scope>" \
oauth.audience="<audience>" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Path to the client assertion file used for authenticating the client. This file is a private key file as an alternative to the client secret.
Alternatively, use oauth.client.assertion
option to specify the client assertion value in clear text.
-
(Optional) Sometimes you may need to specify the client assertion type. In not specified, the default value is urn:ietf:params:oauth:client-assertion-type:jwt-bearer
.
Example password grants configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \ # (1)
oauth.client.secret="<client_secret>" \ # (2)
oauth.password.grant.username="<username>" \ # (3)
oauth.password.grant.password="<password>" \ # (4)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.scope="<scope>" \
oauth.audience="<audience>" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Client ID, which is the name used when creating the client in the authorization server.
-
(Optional) Client secret created when creating the client in the authorization server.
-
Username for password grant authentication. OAuth password grant configuration (username and password) uses the OAuth 2.0 password grant method. To use password grants, create a user account for a client on your authorization server with limited permissions. The account should act like a service account. Use in environments where user accounts are required for authentication, but consider using a refresh token first.
-
Password for password grant authentication.
Note
|
SASL PLAIN does not support passing a username and password (password grants) using the OAuth 2.0 password grant method.
|
Example access token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.access.token="<access_token>" ; # (1)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Long-lived access token for Kafka clients. Alternatively, oauth.access.token.location
can be used to specify the file that contains the access token.
Example Kubernetes service account token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.access.token.location="/var/run/secrets/kubernetes.io/serviceaccount/token"; # (1)
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Location to the service account token on the filesystem (assuming that the client is deployed as a Kubernetes pod)
Example refresh token configuration
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.token.endpoint.uri="<token_endpoint_url>" \
oauth.client.id="<client_id>" \ # (1)
oauth.client.secret="<client_secret>" \ # (2)
oauth.refresh.token="<refresh_token>" \ # (3)
oauth.ssl.truststore.location="/tmp/oauth-truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
-
Client ID, which is the name used when creating the client in the authorization server.
-
(Optional) Client secret created when creating the client in the authorization server.
-
Long-lived refresh token for Kafka clients.
OAuth 2.0 authentication flows depend on the underlying Kafka client and Kafka broker configuration.
The flows must also be supported by the authorization server used.
The Kafka broker listener configuration determines how clients authenticate using an access token.
The client can pass a client ID and secret to request an access token.
If a listener is configured to use PLAIN
authentication, the client can authenticate with a client ID and secret or username and access token.
These values are passed as the username
and password
properties of the PLAIN
mechanism.
Listener configuration supports the following token validation options:
-
You can use fast local token validation based on JWT signature checking and local token introspection, without contacting an authorization server.
The authorization server provides a JWKS endpoint with public certificates that are used to validate signatures on the tokens.
-
You can use a call to a token introspection endpoint provided by an authorization server.
Each time a new Kafka broker connection is established, the broker passes the access token received from the client to the authorization server.
The Kafka broker checks the response to confirm whether the token is valid.
Note
|
An authorization server might only allow the use of opaque access tokens, which means that local token validation is not possible.
|
Kafka client credentials can also be configured for the following types of authentication:
-
Direct local access using a previously generated long-lived access token
-
Contact with the authorization server for a new access token to be issued (using a client ID and credentials, or a refresh token, or a username and a password)
You can use the following communication flows for Kafka authentication using the SASL OAUTHBEARER
mechanism.
Client using client ID and credentials, with broker delegating validation to authorization server
-
The Kafka client requests an access token from the authorization server using a client ID and credentials, and optionally a refresh token. Alternatively, the client may authenticate using a username and a password.
-
The authorization server generates a new access token.
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the access token.
-
The Kafka broker validates the access token by calling a token introspection endpoint on the authorization server using its own client ID and secret.
-
A Kafka client session is established if the token is valid.
Client using client ID and credentials, with broker performing fast local token validation
-
The Kafka client authenticates with the authorization server from the token endpoint, using a client ID and credentials, and optionally a refresh token. Alternatively, the client may authenticate using a username and a password.
-
The authorization server generates a new access token.
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the access token.
-
The Kafka broker validates the access token locally using a JWT token signature check, and local token introspection.
Client using long-lived access token, with broker delegating validation to authorization server
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the long-lived access token.
-
The Kafka broker validates the access token by calling a token introspection endpoint on the authorization server, using its own client ID and secret.
-
A Kafka client session is established if the token is valid.
Client using long-lived access token, with broker performing fast local validation
-
The Kafka client authenticates with the Kafka broker using the SASL OAUTHBEARER
mechanism to pass the long-lived access token.
-
The Kafka broker validates the access token locally using a JWT token signature check and local token introspection.
Warning
|
Fast local JWT token signature validation is suitable only for short-lived tokens as there is no check with the authorization server if a token has been revoked.
Token expiration is written into the token, but revocation can happen at any time, so cannot be accounted for without contacting the authorization server.
Any issued token would be considered valid until it expires.
|
You can use the following communication flows for Kafka authentication using the OAuth PLAIN
mechanism.
Client using a client ID and secret, with the broker obtaining the access token for the client
-
The Kafka client passes a clientId
as a username and a secret
as a password.
-
The Kafka broker uses a token endpoint to pass the clientId
and secret
to the authorization server.
-
The authorization server returns a fresh access token or an error if the client credentials are not valid.
-
The Kafka broker validates the token in one of the following ways:
-
If a token introspection endpoint is specified, the Kafka broker validates the access token by calling the endpoint on the authorization server.
A session is established if the token validation is successful.
-
If local token introspection is used, a request is not made to the authorization server.
The Kafka broker validates the access token locally using a JWT token signature check.
Client using a long-lived access token without a client ID and secret
-
The Kafka client passes a username and password. The password provides the value of an access token that was obtained manually and configured before running the client.
-
The password is passed with or without an $accessToken:
string prefix depending on whether or not the Kafka broker listener is configured with a token endpoint for authentication.
-
If the token endpoint is configured, the password should be prefixed by $accessToken:
to let the broker know that the password parameter contains an access token rather than a client secret. The Kafka broker interprets the username as the account username.
-
If the token endpoint is not configured on the Kafka broker listener (enforcing a no-client-credentials mode
), the password should provide the access token without the prefix. The Kafka broker interprets the username as the account username.
In this mode, the client doesn’t use a client ID and secret, and the password
parameter is always interpreted as a raw access token.
-
The Kafka broker validates the token in one of the following ways:
-
If a token introspection endpoint is specified, the Kafka broker validates the access token by calling the endpoint on the authorization server. A session is established if token validation is successful.
-
If local token introspection is used, there is no request made to the authorization server. Kafka broker validates the access token locally using a JWT token signature check.
Configure oauth
listeners to use Kafka session re-authentication for OAuth 2.0 sessions between Kafka clients and Kafka.
This mechanism enforces the expiry of an authenticated session between the client and the broker after a defined period of time.
When a session expires, the client immediately starts a new session by reusing the existing connection rather than dropping it.
Session re-authentication is disabled by default.
To enable it, you set a time value for maxSecondsWithoutReauthentication
in the oauth
listener configuration.
The same property is used to configure session re-authentication for OAUTHBEARER
and PLAIN
authentication.
For an example configuration, see Configuring OAuth 2.0 authentication on listeners.
Session re-authentication must be supported by the Kafka client libraries used by the client.
Session re-authentication can be used with fast local JWT or introspection endpoint token validation.
Client re-authentication
When the broker’s authenticated session expires, the client must re-authenticate to the existing session by sending a new, valid access token to the broker, without dropping the connection.
If token validation is successful, a new client session is started using the existing connection.
If the client fails to re-authenticate, the broker will close the connection if further attempts are made to send or receive messages.
Java clients that use Kafka client library 2.2 or later automatically re-authenticate if the re-authentication mechanism is enabled on the broker.
Session re-authentication also applies to refresh tokens, if used.
When the session expires, the client refreshes the access token by using its refresh token.
The client then uses the new access token to re-authenticate to the existing session.
Session expiry
When session re-authentication is configured, session expiry works differently for OAUTHBEARER
and PLAIN
authentication.
For OAUTHBEARER
and PLAIN
, using the client ID and secret method:
For PLAIN
using the long-lived access token method:
-
The broker’s authenticated session will expire at the configured maxSecondsWithoutReauthentication
.
-
Re-authentication will fail if the access token expires before the configured time.
Although session re-authentication is attempted, PLAIN
has no mechanism for refreshing tokens.
If maxSecondsWithoutReauthentication
is not configured, OAUTHBEARER
and PLAIN
clients can remain connected to brokers indefinitely, without needing to re-authenticate.
Authenticated sessions do not end with access token expiry.
However, this can be considered when configuring authorization, for example, by using keycloak
authorization or installing a custom authorizer.
This example shows how to configure client access to a Kafka cluster using OAUth 2.0 authentication.
The procedures describe the configuration required to set up OAuth 2.0 authentication on Kafka listeners, Kafka Java clients, and Kafka components.
Configure Kafka listeners so that they are enabled to use OAuth 2.0 authentication using an authorization server.
We advise using OAuth 2.0 over an encrypted interface through through a listener with tls: true
.
Plain listeners are not recommended.
If the authorization server is using certificates signed by the trusted CA and matching the OAuth 2.0 server hostname, TLS connection works using the default settings.
Otherwise, you may need to configure the truststore with proper certificates or disable the certificate hostname validation.
Procedure
-
Specify a listener in the Kafka
resource with an oauth
authentication type.
Example listener configuration with OAuth 2.0 authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
kafka:
# ...
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: oauth
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
#...
-
Configure the OAuth listener depending on the authorization server and validation type:
-
Apply the changes to the Kafka
configuration.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c ${CONTAINER_NAME}
kubectl get pod -w
The rolling update configures the brokers to use OAuth 2.0 authentication.
Configure Kafka producer and consumer APIs to use OAuth 2.0 for interaction with Kafka brokers.
Add a callback plugin to your client pom.xml
file, then configure your client for OAuth 2.0.
How you configure the authentication properties depends on the authentication method you are using to access the OAuth 2.0 authorization server.
In this procedure, the properties are specified in a properties file, then loaded into the client configuration.
Prerequisites
-
Strimzi and Kafka are running
-
An OAuth 2.0 authorization server is deployed and configured for OAuth access to Kafka brokers
-
Kafka brokers are configured for OAuth 2.0
Procedure
-
Add the client library with OAuth 2.0 support to the pom.xml
file for the Kafka client:
<dependency>
<groupId>io.strimzi</groupId>
<artifactId>kafka-oauth-client</artifactId>
<version>0.15.0</version>
</dependency>
-
Configure the client depending on the OAuth 2.0 authentication method:
For example, specify the properties for the authentication method in a client.properties
file.
-
Input the client properties for OAUTH 2.0 authentication into the Java client code.
Example showing input of client properties
Properties props = new Properties();
try (FileReader reader = new FileReader("client.properties", StandardCharsets.UTF_8)) {
props.load(reader);
}
-
Verify that the Kafka client can access the Kafka brokers.
This procedure describes how to set up Kafka components to use OAuth 2.0 authentication using an authorization server.
You can configure OAuth 2.0 authentication for the following components:
-
Kafka Connect
-
Kafka MirrorMaker
-
Kafka Bridge
In this scenario, the Kafka component and the authorization server are running in the same cluster.
Prerequisites
-
Strimzi and Kafka are running
-
An OAuth 2.0 authorization server is deployed and configured for OAuth access to Kafka brokers
-
Kafka brokers are configured for OAuth 2.0
Procedure
-
Create a client secret and mount it to the component as an environment variable.
For example, here we are creating a client Secret
for the Kafka Bridge:
apiVersion: kafka.strimzi.io/v1beta2
kind: Secret
metadata:
name: my-bridge-oauth
type: Opaque
data:
clientSecret: MGQ1OTRmMzYtZTllZS00MDY2LWI5OGEtMTM5MzM2NjdlZjQw # (1)
-
The clientSecret
key must be in base64 format.
-
Create or edit the resource for the Kafka component so that OAuth 2.0 authentication is configured for the authentication property.
For OAuth 2.0 authentication, you can use the following options:
For example, here OAuth 2.0 is assigned to the Kafka Bridge client using a client ID and secret, and TLS:
Example OAuth 2.0 authentication configuration using the client secret
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth # (1)
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint> # (2)
clientId: kafka-bridge
clientSecret:
secretName: my-bridge-oauth
key: clientSecret
tlsTrustedCertificates: # (3)
- secretName: oauth-server-cert
pattern: "*.crt"
-
Authentication type set to oauth
.
-
URI of the token endpoint for authentication.
-
Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
In this example, OAuth 2.0 is assigned to the Kafka Bridge client using a client ID and the location of a client assertion file, with TLS to connect to the authorization server:
Example OAuth 2.0 authentication configuration using client assertion
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth
tokenEndpointUri: https://<auth_server_address>/<path_to_token_endpoint>
clientId: kafka-bridge
clientAssertionLocation: /var/run/secrets/sso/assertion # (1)
tlsTrustedCertificates:
- secretName: oauth-server-cert
pattern: "*.crt"
-
Filesystem path to the client assertion file used for authenticating the client.
This file is typically added to the deployed pod by an external operator service.
Alternatively, use clientAssertion
to refer to a secret containing the client assertion value.
Here, OAuth 2.0 is assigned to the Kafka Bridge client using a service account token:
Example OAuth 2.0 authentication configuration using the service account token
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
authentication:
type: oauth
accessTokenLocation: /var/run/secrets/kubernetes.io/serviceaccount/token # (1)
-
Path to the service account token file location.
Depending on how you apply OAuth 2.0 authentication, and the type of authorization server, there are additional configuration options you can use:
Additional configuration options
# ...
spec:
# ...
authentication:
# ...
disableTlsHostnameVerification: true # (1)
accessTokenIsJwt: false # (2)
scope: any # (3)
audience: kafka # (4)
connectTimeoutSeconds: 60 # (5)
readTimeoutSeconds: 60 # (6)
httpRetries: 2 # (7)
httpRetryPauseMs: 300 # (8)
includeAcceptHeader: false # (9)
-
(Optional) Disable TLS hostname verification. Default is false
.
-
If you are using opaque tokens, you can apply accessTokenIsJwt: false
so that access tokens are not treated as JWT tokens.
-
(Optional) The scope
for requesting the token from the token endpoint.
An authorization server may require a client to specify the scope.
In this case it is any
.
-
(Optional) The audience
for requesting the token from the token endpoint.
An authorization server may require a client to specify the audience.
In this case it is kafka
.
-
(Optional) The connect timeout in seconds when connecting to the authorization server. The default value is 60.
-
(Optional) The read timeout in seconds when connecting to the authorization server. The default value is 60.
-
(Optional) The maximum number of times to retry a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make the Kafka broker unresponsive.
-
(Optional) The time to wait before attempting another retry of a failed HTTP request to the authorization server. By default, this time is set to zero, meaning that no pause is applied. This is because many issues that cause failed requests are per-request network glitches or proxy issues that can be resolved quickly. However, if your authorization server is under stress or experiencing high traffic, you may want to set this option to a value of 100 ms or more to reduce the load on the server and increase the likelihood of successful retries.
-
(Optional) Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
-
Apply the changes to the resource configuration of the component.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c ${CONTAINER_NAME}
kubectl get pod -w
The rolling updates configure the component for interaction with Kafka brokers using OAuth 2.0 authentication.
Strimzi supports the use of OAuth 2.0 token-based authorization through Keycloak Authorization Services,
which lets you manage security policies and permissions centrally.
Security policies and permissions defined in Keycloak grant access to Kafka resources.
Users and clients are matched against policies that permit access to perform specific actions on Kafka brokers.
Kafka allows all users full access to brokers by default, but also provides the AclAuthorizer
and StandardAuthorizer
plugins to configure authorization based on Access Control Lists (ACLs).
The ACL rules managed by these plugins are used to grant or deny access to resources based on username, and these rules are stored within the Kafka cluster itself.
However, OAuth 2.0 token-based authorization with Keycloak offers far greater flexibility on how you wish to implement access control to Kafka brokers.
In addition, you can configure your Kafka brokers to use OAuth 2.0 authorization and ACLs.
This example procedure shows how to configure Kafka to use OAuth 2.0 authorization using Keycloak Authorization Services.
To enable OAuth 2.0 authorization using Keycloak, configure the Kafka
resource to use keycloak
authorization and specify the properties required to access the authorization server and Keycloak Authorization Services.
Keycloak server Authorization Services REST endpoints extend token-based authentication with Keycloak by applying defined security policies on a particular user,
and providing a list of permissions granted on different resources for that user.
Policies use roles and groups to match permissions to users.
OAuth 2.0 authorization enforces permissions locally based on the received list of grants for the user from Keycloak Authorization Services.
A Keycloak authorizer (KeycloakAuthorizer
) is provided with Strimzi.
The authorizer fetches a list of granted permissions from the authorization server as needed,
and enforces authorization locally on Kafka, making rapid authorization decisions for each client request.
Before you begin
Consider the access you require or want to limit for certain users.
You can use a combination of Keycloak groups, roles, clients, and users to configure access in Keycloak.
Typically, groups are used to match users based on organizational departments or geographical locations.
And roles are used to match users based on their function.
With Keycloak, you can store users and groups in LDAP, whereas clients and roles cannot be stored this way.
Storage and access to user data may be a factor in how you choose to configure authorization policies.
Note
|
Super users always have unconstrained access to Kafka regardless of the authorization implemented.
|
Prerequisites
-
Strimzi must be configured to use OAuth 2.0 with Keycloak for token-based authentication.
You use the same Keycloak server endpoint when you set up authorization.
-
OAuth 2.0 authentication must be configured with the maxSecondsWithoutReauthentication
option to enable re-authentication.
Procedure
-
Access the Keycloak Admin Console or use the Keycloak Admin CLI to enable Authorization Services for the OAuth 2.0 client for Kafka you created when setting up OAuth 2.0 authentication.
-
Use Authorization Services to define resources, authorization scopes, policies, and permissions for the client.
-
Bind the permissions to users and clients by assigning them roles and groups.
-
Configure the kafka
resource to use keycloak
authorization, and to be able to access the authorization server and Authorization Services.
Example OAuth 2.0 authorization configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
authorization:
type: keycloak (1)
tokenEndpointUri: <https://<auth-server-address>/realms/external/protocol/openid-connect/token> (2)
clientId: kafka (3)
delegateToKafkaAcls: false (4)
disableTlsHostnameVerification: false (5)
superUsers: (6)
- CN=user-1
- user-2
- CN=user-3
tlsTrustedCertificates: (7)
- secretName: oauth-server-cert
pattern: "*.crt"
grantsRefreshPeriodSeconds: 60 (8)
grantsRefreshPoolSize: 5 (9)
grantsMaxIdleSeconds: 300 (10)
grantsGcPeriodSeconds: 300 (11)
grantsAlwaysLatest: false (12)
connectTimeoutSeconds: 60 (13)
readTimeoutSeconds: 60 (14)
httpRetries: 2 (15)
enableMetrics: false (16)
includeAcceptHeader: false (17)
#...
-
Type keycloak
enables Keycloak authorization.
-
URI of the Keycloak token endpoint. For production, always use https://
urls.
When you configure token-based oauth
authentication, you specify a jwksEndpointUri
as the URI for local JWT validation.
The hostname for the tokenEndpointUri
URI must be the same.
-
The client ID of the OAuth 2.0 client definition in Keycloak that has Authorization Services enabled. Typically, kafka
is used as the ID.
-
(Optional) Delegate authorization to Kafka AclAuthorizer
and StandardAuthorizer
if access is denied by Keycloak Authorization Services policies.
Default is false
.
-
(Optional) Disable TLS hostname verification. Default is false
.
-
(Optional) Designated super users.
-
(Optional) Certificates stored in X.509 format within the specified secrets for TLS connection to the authorization server.
-
(Optional) The time between two consecutive grants refresh runs. That is the maximum time for active sessions to detect any permissions changes for the user on Keycloak. The default value is 60.
-
(Optional) The number of threads to use to refresh (in parallel) the grants for the active sessions. The default value is 5.
-
(Optional) The time, in seconds, after which an idle grant in the cache can be evicted. The default value is 300.
-
(Optional) The time, in seconds, between consecutive runs of a job that cleans stale grants from the cache. The default value is 300.
-
(Optional) Controls whether the latest grants are fetched for a new session. When enabled, grants are retrieved from Keycloak and cached for the user. The default value is false
.
-
(Optional) The connect timeout in seconds when connecting to the Keycloak token endpoint. The default value is 60.
-
(Optional) The read timeout in seconds when connecting to the Keycloak token endpoint. The default value is 60.
-
(Optional) The maximum number of times to retry (without pausing) a failed HTTP request to the authorization server. The default value is 0
, meaning that no retries are performed. To use this option effectively, consider reducing the timeout times for the connectTimeoutSeconds
and readTimeoutSeconds
options. However, note that retries may prevent the current worker thread from being available to other requests, and if too many requests stall, it could make Kafka unresponsive.
-
(Optional) Enable or disable OAuth metrics. The default value is false
.
-
(Optional) Some authorization servers have issues with client sending Accept: application/json
header. By setting includeAcceptHeader: false
the header will not be sent. Default is true
.
-
Apply the changes to the Kafka
configuration.
-
Check the update in the logs or by watching the pod state transitions:
kubectl logs -f ${POD_NAME} -c kafka
kubectl get pod -w
The rolling update configures the brokers to use OAuth 2.0 authorization.
-
Verify the configured permissions by accessing Kafka brokers as clients or users with specific roles, ensuring they have the necessary access and do not have unauthorized access.
When using Keycloak as the OAuth 2.0 authorization server, Kafka permissions are granted to user accounts or service accounts using authorization permissions.
To grant permissions to access Kafka, create an OAuth client specification in Keycloak that maps the authorization models of Keycloak Authorization Services and Kafka.
Kafka and Keycloak Authorization Services use different authorization models.
Kafka authorization model
When a Kafka client performs an action on a broker, the broker uses the configured KeycloakAuthorizer
to check the client’s permissions, based on the action and resource type.
Each resource type has a set of available permissions for operations.
For example, the Topic
resource type has Create
and Write
permissions among others.
Keycloak Authorization Services model
The Keycloak Authorization Services model defines authorized actions.
- Resources
-
Resources are matched with permitted actions.
A resource might be an individual topic, for example, or all topics with names starting with the same prefix.
A resource definition is associated with a set of available authorization scopes, which represent a set of all actions available on the resource.
Often, only a subset of these actions is actually permitted.
- Authorization scopes
-
An authorization scope is a set of all the available actions on a specific resource definition.
When you define a new resource, you add scopes from the set of all scopes.
- Policies
-
A policy is an authorization rule that uses criteria to match against a list of accounts.
Policies can match:
-
Service accounts based on client ID or roles
-
User accounts based on username, groups, or roles.
- Permissions
-
A permission grants a subset of authorization scopes on a specific resource definition to a set of users.
The Kafka authorization model is used as a basis for defining the Keycloak roles and resources that control access to Kafka.
To grant Kafka permissions to user accounts or service accounts, you first create an OAuth client specification in Keycloak for the Kafka cluster.
You then specify Keycloak Authorization Services rules on the client.
Typically, the client ID of the OAuth client that represents the Kafka cluster is kafka
.
The example configuration files provided with Strimzi use kafka
as the OAuth client id.
Note
|
If you have multiple Kafka clusters, you can use a single OAuth client (kafka ) for all of them.
This gives you a single, unified space in which to define and manage authorization rules.
However, you can also use different OAuth client ids (for example, my-cluster-kafka or cluster-dev-kafka ) and define authorization rules for each cluster within each client configuration.
|
The kafka
client definition must have the Authorization Enabled option enabled in the Keycloak Admin Console.
All permissions exist within the scope of the kafka
client.
If you have different Kafka clusters configured with different OAuth client IDs, they each need a separate set of permissions even though they’re part of the same Keycloak realm.
When the Kafka client uses OAUTHBEARER authentication, the Keycloak authorizer (KeycloakAuthorizer
) uses the access token of the current session to retrieve a list of grants from the Keycloak server.
To grant permissions, the authorizer evaluates the grants list (received and cached) from Keycloak Authorization Services based on the access token owner’s policies and permissions.
Uploading authorization scopes for Kafka permissions
An initial Keycloak configuration usually involves uploading authorization scopes to create a list of all possible actions that can be performed on each Kafka resource type.
This step is performed once only, before defining any permissions.
You can add authorization scopes manually instead of uploading them.
Authorization scopes should contain the following Kafka permissions regardless of the resource type:
-
Create
-
Write
-
Read
-
Delete
-
Describe
-
Alter
-
DescribeConfigs
-
AlterConfigs
-
ClusterAction
-
IdempotentWrite
If you’re certain you won’t need a permission (for example, IdempotentWrite
), you can omit it from the list of authorization scopes.
However, that permission won’t be available to target on Kafka resources.
Note
|
The All permission is not supported.
|
Resource patterns for permissions checks
Resource patterns are used for pattern matching against the targeted resources when performing permission checks.
The general pattern format is <resource_type>:<pattern_name>
.
The resource types mirror the Kafka authorization model.
The pattern allows for two matching options:
Example patterns for resources
Topic:my-topic
Topic:orders-*
Group:orders-*
Cluster:*
Additionally, the general pattern format can be prefixed by kafka-cluster:<cluster_name>
followed by a comma, where <cluster_name>
refers to the metadata.name
in the Kafka custom resource.
Example patterns for resources with cluster prefix
kafka-cluster:my-cluster,Topic:*
kafka-cluster:*,Group:b_*
When the kafka-cluster
prefix is missing, it is assumed to be kafka-cluster:*
.
When defining a resource, you can associate it with a list of possible authorization scopes which are relevant to the resource.
Set whatever actions make sense for the targeted resource type.
Though you may add any authorization scope to any resource, only the scopes supported by the resource type are considered for access control.
Policies for applying access permission
Policies are used to target permissions to one or more user accounts or service accounts.
Targeting can refer to:
A policy is given a unique name and can be reused to target multiple permissions to multiple resources.
Permissions to grant access
Use fine-grained permissions to pull together the policies, resources, and authorization scopes that grant access to users.
The name of each permission should clearly define which permissions it grants to which users.
For example, Dev Team B can read from topics starting with x
.
The following examples demonstrate the user permissions required for performing common operations on Kafka.
Create a topic
To create a topic, the Create
permission is required for the specific topic, or for Cluster:kafka-cluster
.
bin/kafka-topics.sh --create --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
List topics
If a user has the Describe
permission on a specified topic, the topic is listed.
bin/kafka-topics.sh --list \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display topic details
To display a topic’s details, Describe
and DescribeConfigs
permissions are required on the topic.
bin/kafka-topics.sh --describe --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Produce messages to a topic
To produce messages to a topic, Describe
and Write
permissions are required on the topic.
If the topic hasn’t been created yet, and topic auto-creation is enabled, the permissions to create a topic are required.
bin/kafka-console-producer.sh --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --producer.config=/tmp/config.properties
Consume messages from a topic
To consume messages from a topic, Describe
and Read
permissions are required on the topic.
Consuming from the topic normally relies on storing the consumer offsets in a consumer group, which requires additional Describe
and Read
permissions on the consumer group.
Two resources
are needed for matching. For example:
Topic:my-topic
Group:my-group-*
bin/kafka-console-consumer.sh --topic my-topic --group my-group-1 --from-beginning \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --consumer.config /tmp/config.properties
Produce messages to a topic using an idempotent producer
As well as the permissions for producing to a topic, an additional IdempotentWrite
permission is required on the
Cluster:kafka-cluster
resource.
Two resources
are needed for matching. For example:
Topic:my-topic
Cluster:kafka-cluster
bin/kafka-console-producer.sh --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --producer.config=/tmp/config.properties --producer-property enable.idempotence=true --request-required-acks -1
List consumer groups
When listing consumer groups, only the groups on which the user has the Describe
permissions are returned.
Alternatively, if the user has the Describe
permission on the Cluster:kafka-cluster
, all the consumer groups are returned.
bin/kafka-consumer-groups.sh --list \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display consumer group details
To display a consumer group’s details, the Describe
permission is required on the group and the topics associated with the group.
bin/kafka-consumer-groups.sh --describe --group my-group-1 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Change topic configuration
To change a topic’s configuration, the Describe
and Alter
permissions are required on the topic.
bin/kafka-topics.sh --alter --topic my-topic --partitions 2 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Display Kafka broker configuration
In order to use kafka-configs.sh
to get a broker’s configuration, the DescribeConfigs
permission is required on the
Cluster:kafka-cluster
.
bin/kafka-configs.sh --entity-type brokers --entity-name 0 --describe --all \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Change Kafka broker configuration
To change a Kafka broker’s configuration, DescribeConfigs
and AlterConfigs
permissions are required on Cluster:kafka-cluster
.
bin/kafka-configs --entity-type brokers --entity-name 0 --alter --add-config log.cleaner.threads=2 \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Delete a topic
To delete a topic, the Describe
and Delete
permissions are required on the topic.
bin/kafka-topics.sh --delete --topic my-topic \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config=/tmp/config.properties
Select a lead partition
To run leader selection for topic partitions, the Alter
permission is required on the Cluster:kafka-cluster
.
bin/kafka-leader-election.sh --topic my-topic --partition 0 --election-type PREFERRED /
--bootstrap-server my-cluster-kafka-bootstrap:9092 --admin.config /tmp/config.properties
Reassign partitions
To generate a partition reassignment file, Describe
permissions are required on the topics involved.
bin/kafka-reassign-partitions.sh --topics-to-move-json-file /tmp/topics-to-move.json --broker-list "0,1" --generate \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties > /tmp/partition-reassignment.json
To execute the partition reassignment, Describe
and Alter
permissions are required on Cluster:kafka-cluster
. Also,
Describe
permissions are required on the topics involved.
bin/kafka-reassign-partitions.sh --reassignment-json-file /tmp/partition-reassignment.json --execute \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties
To verify partition reassignment, Describe
, and AlterConfigs
permissions are required on Cluster:kafka-cluster
, and on each
of the topics involved.
bin/kafka-reassign-partitions.sh --reassignment-json-file /tmp/partition-reassignment.json --verify \
--bootstrap-server my-cluster-kafka-bootstrap:9092 --command-config /tmp/config.properties
If you are using OAuth 2.0 with Keycloak for token-based authentication,
you can also use Keycloak to configure authorization rules to constrain client access to Kafka brokers.
This example explains how to use Keycloak Authorization Services with keycloak
authorization.
Set up Keycloak Authorization Services to enforce access restrictions on Kafka clients.
Keycloak Authorization Services use authorization scopes, policies and permissions to define and apply access control to resources.
Keycloak Authorization Services REST endpoints provide a list of granted permissions on resources for authenticated users.
The list of grants (permissions) is fetched from the Keycloak server as the first action after an authenticated session is established by the Kafka client.
The list is refreshed in the background so that changes to the grants are detected.
Grants are cached and enforced locally on the Kafka broker for each user session to provide fast authorization decisions.
kafka-ephemeral-oauth-single-keycloak-authz.yaml
-
An example Kafka
custom resource configured for OAuth 2.0 token-based authorization using Keycloak.
You can use the custom resource to deploy a Kafka cluster that uses keycloak
authorization and token-based oauth
authentication.
kafka-authz-realm.json
-
An example Keycloak realm configured with sample groups, users, roles and clients.
You can import the realm into a Keycloak instance to set up fine-grained permissions to access Kafka.
If you want to try the example with Keycloak, use these files to perform the tasks outlined in this section in the order shown.
Authentication
When you configure token-based oauth
authentication, you specify a jwksEndpointUri
as the URI for local JWT validation.
When you configure keycloak
authorization, you specify a tokenEndpointUri
as the URI of the Keycloak token endpoint.
The hostname for both URIs must be the same.
Targeted permissions with group or role policies
In Keycloak, confidential clients with service accounts enabled can authenticate to the server in their own name using a client ID and a secret.
This is convenient for microservices that typically act in their own name, and not as agents of a particular user (like a web site).
Service accounts can have roles assigned like regular users.
They cannot, however, have groups assigned.
As a consequence, if you want to target permissions to microservices using service accounts, you cannot use group policies, and should instead use role policies.
Conversely, if you want to limit certain permissions only to regular user accounts where authentication with a username and password is required, you can achieve that as a side effect of using the group policies rather than the role policies.
This is what is used in this example for permissions that start with ClusterManager
.
Performing cluster management is usually done interactively using CLI tools.
It makes sense to require the user to log in before using the resulting access token to authenticate to the Kafka broker.
In this case, the access token represents the specific user, rather than the client application.
Set up Keycloak, then connect to its Admin Console and add the preconfigured realm.
Use the example kafka-authz-realm.json
file to import the realm.
You can check the authorization rules defined for the realm in the Admin Console.
The rules grant access to the resources on the Kafka cluster configured to use the example Keycloak realm.
Procedure
-
Install the Keycloak server using the Keycloak Operator as described in Installing the Keycloak Operator in the Keycloak documentation.
-
Wait until the Keycloak instance is running.
-
Get the external hostname to be able to access the Admin Console.
NS=sso
kubectl get ingress keycloak -n $NS
In this example, we assume the Keycloak server is running in the sso
namespace.
-
Get the password for the admin
user.
kubectl get -n $NS pod keycloak-0 -o yaml | less
The password is stored as a secret, so get the configuration YAML file for the Keycloak instance to identify the name of the secret (secretKeyRef.name
).
-
Use the name of the secret to obtain the clear text password.
SECRET_NAME=credential-keycloak
kubectl get -n $NS secret $SECRET_NAME -o yaml | grep PASSWORD | awk '{print $2}' | base64 -D
In this example, we assume the name of the secret is credential-keycloak
.
-
Log in to the Admin Console with the username admin
and the password you obtained.
Use https://HOSTNAME
to access the Kubernetes Ingress
.
You can now upload the example realm to Keycloak using the Admin Console.
-
Click Add Realm to import the example realm.
-
Add the examples/security/keycloak-authorization/kafka-authz-realm.json
file, and then click Create.
You now have kafka-authz
as your current realm in the Admin Console.
The default view displays the Master realm.
-
In the Keycloak Admin Console, go to Clients > kafka > Authorization > Settings and check that Decision Strategy is set to Affirmative.
An affirmative policy means that at least one policy must be satisfied for a client to access the Kafka cluster.
-
In the Keycloak Admin Console, go to Groups, Users, Roles and Clients to view the realm configuration.
- Groups
-
Groups
are used to create user groups and set user permissions. Groups are sets of users with a name assigned. They are used to compartmentalize users into geographical, organizational or departmental units.
Groups can be linked to an LDAP identity provider. You can make a user a member of a group through a custom LDAP server admin user interface, for example, to grant permissions on Kafka resources.
- Users
-
Users
are used to create users. For this example, alice
and bob
are defined. alice
is a member of the ClusterManager
group and bob
is a member of ClusterManager-my-cluster
group.
Users can be stored in an LDAP identity provider.
- Roles
-
Roles
mark users or clients as having certain permissions.
Roles are a concept analogous to groups. They are usually used to tag users with organizational roles and have the requisite permissions.
Roles cannot be stored in an LDAP identity provider.
If LDAP is a requirement, you can use groups instead, and add Keycloak roles to the groups so that when users are assigned a group they also get a corresponding role.
- Clients
-
Clients
can have specific configurations. For this example, kafka
, kafka-cli
, team-a-client
, and team-b-client
clients are configured.
-
The kafka
client is used by Kafka brokers to perform the necessary OAuth 2.0 communication for access token validation.
This client also contains the authorization services resource definitions, policies, and authorization scopes used to perform authorization on the Kafka brokers.
The authorization configuration is defined in the kafka
client from the Authorization tab, which becomes visible when Authorization Enabled is switched on from the Settings tab.
-
The kafka-cli
client is a public client that is used by the Kafka command line tools when authenticating with username and password to obtain an access token or a refresh token.
-
The team-a-client
and team-b-client
clients are confidential clients representing services with partial access to certain Kafka topics.
-
In the Keycloak Admin Console, go to Authorization > Permissions to see the granted permissions that use the resources and policies defined for the realm.
For example, the kafka
client has the following permissions:
Dev Team A can write to topics that start with x_ on any cluster
Dev Team B can read from topics that start with x_ on any cluster
Dev Team B can update consumer group offsets that start with x_ on any cluster
ClusterManager of my-cluster Group has full access to cluster config on my-cluster
ClusterManager of my-cluster Group has full access to consumer groups on my-cluster
ClusterManager of my-cluster Group has full access to topics on my-cluster
- Dev Team A
-
The Dev Team A realm role can write to topics that start with x_
on any cluster. This combines a resource called Topic:x_*
, Describe
and Write
scopes, and the Dev Team A
policy. The Dev Team A
policy matches all users that have a realm role called Dev Team A
.
- Dev Team B
-
The Dev Team B realm role can read from topics that start with x_
on any cluster. This combines Topic:x_*
, Group:x_*
resources, Describe
and Read
scopes, and the Dev Team B
policy. The Dev Team B
policy matches all users that have a realm role called Dev Team B
. Matching users and clients have the ability to read from topics, and update the consumed offsets for topics and consumer groups that have names starting with x_
.
Deploy a Kafka cluster configured to connect to the Keycloak server.
Use the example kafka-ephemeral-oauth-single-keycloak-authz.yaml
file to deploy the Kafka cluster as a Kafka
custom resource.
The example deploys a single-node Kafka cluster with keycloak
authorization and oauth
authentication.
Prerequisites
-
The Keycloak authorization server is deployed to your Kubernetes cluster and loaded with the example realm.
-
The Cluster Operator is deployed to your Kubernetes cluster.
-
The Strimzi examples/security/keycloak-authorization/kafka-ephemeral-oauth-single-keycloak-authz.yaml
custom resource.
Procedure
-
Use the hostname of the Keycloak instance you deployed to prepare a truststore certificate for Kafka brokers to communicate with the Keycloak server.
SSO_HOST=SSO-HOSTNAME
SSO_HOST_PORT=$SSO_HOST:443
STOREPASS=storepass
echo "Q" | openssl s_client -showcerts -connect $SSO_HOST_PORT 2>/dev/null | awk ' /BEGIN CERTIFICATE/,/END CERTIFICATE/ { print $0 } ' > /tmp/sso.pem
The certificate is required as Kubernetes Ingress
is used to make a secure (HTTPS) connection.
Usually there is not one single certificate, but a certificate chain. You only have to provide the top-most issuer CA, which is listed last in the /tmp/sso.pem
file.
You can extract it manually or using the following commands:
Example command to extract the top CA certificate in a certificate chain
split -p "-----BEGIN CERTIFICATE-----" sso.pem sso-
for f in $(ls sso-*); do mv $f $f.pem; done
cp $(ls sso-* | sort -r | head -n 1) sso-ca.crt
Note
|
A trusted CA certificate is normally obtained from a trusted source, and not by using the openssl command.
|
-
Deploy the certificate to Kubernetes as a secret.
kubectl create secret generic oauth-server-cert --from-file=/tmp/sso-ca.crt -n $NS
-
Set the hostname as an environment variable
-
Create and deploy the example Kafka cluster.
cat examples/security/keycloak-authorization/kafka-ephemeral-oauth-single-keycloak-authz.yaml | sed -E 's#\${SSO_HOST}'"#$SSO_HOST#" | kubectl create -n $NS -f -
Create a new pod for an interactive CLI session.
Set up a truststore with a Keycloak certificate for TLS connectivity.
The truststore is to connect to Keycloak and the Kafka broker.
Prerequisites
-
The Keycloak authorization server is deployed to your Kubernetes cluster and loaded with the example realm.
In the Keycloak Admin Console, check the roles assigned to the clients are displayed in Clients > Service Account Roles.
-
The Kafka cluster configured to connect with Keycloak is deployed to your Kubernetes cluster.
Procedure
-
Run a new interactive pod container using the Kafka image to connect to a running Kafka broker.
NS=sso
kubectl run -ti --restart=Never --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 kafka-cli -n $NS -- /bin/sh
Note
|
If kubectl times out waiting on the image download, subsequent attempts may result in an AlreadyExists error.
|
-
Attach to the pod container.
kubectl attach -ti kafka-cli -n $NS
-
Use the hostname of the Keycloak instance to prepare a certificate for client connection using TLS.
SSO_HOST=SSO-HOSTNAME
SSO_HOST_PORT=$SSO_HOST:443
STOREPASS=storepass
echo "Q" | openssl s_client -showcerts -connect $SSO_HOST_PORT 2>/dev/null | awk ' /BEGIN CERTIFICATE/,/END CERTIFICATE/ { print $0 } ' > /tmp/sso.pem
Usually there is not one single certificate, but a certificate chain. You only have to provide the top-most issuer CA, which is listed last in the /tmp/sso.pem
file.
You can extract it manually or using the following command:
Example command to extract the top CA certificate in a certificate chain
split -p "-----BEGIN CERTIFICATE-----" sso.pem sso-
for f in $(ls sso-*); do mv $f $f.pem; done
cp $(ls sso-* | sort -r | head -n 1) sso-ca.crt
Note
|
A trusted CA certificate is normally obtained from a trusted source, and not by using the openssl command.
|
-
Create a truststore for TLS connection to the Kafka brokers.
keytool -keystore /tmp/truststore.p12 -storetype pkcs12 -alias sso -storepass $STOREPASS -import -file /tmp/sso-ca.crt -noprompt
-
Use the Kafka bootstrap address as the hostname of the Kafka broker and the tls
listener port (9093) to prepare a certificate for the Kafka broker.
KAFKA_HOST_PORT=my-cluster-kafka-bootstrap:9093
STOREPASS=storepass
echo "Q" | openssl s_client -showcerts -connect $KAFKA_HOST_PORT 2>/dev/null | awk ' /BEGIN CERTIFICATE/,/END CERTIFICATE/ { print $0 } ' > /tmp/my-cluster-kafka.pem
The obtained .pem
file is usually not one single certificate, but a certificate chain. You only have to provide the top-most issuer CA, which is listed last in the /tmp/my-cluster-kafka.pem
file.
You can extract it manually or using the following command:
Example command to extract the top CA certificate in a certificate chain
split -p "-----BEGIN CERTIFICATE-----" /tmp/my-cluster-kafka.pem kafka-
for f in $(ls kafka-*); do mv $f $f.pem; done
cp $(ls kafka-* | sort -r | head -n 1) my-cluster-kafka-ca.crt
Note
|
A trusted CA certificate is normally obtained from a trusted source, and not by using the openssl command.
For this example we assume the client is running in a pod in the same namespace where the Kafka cluster was deployed.
If the client is accessing the Kafka cluster from outside the Kubernetes cluster, you would have to first determine the bootstrap address.
In that case you can also get the cluster certificate directly from the Kubernetes secret, and there is no need for openssl .
For more information, see Setting up client access to a Kafka cluster.
|
-
Add the certificate for the Kafka broker to the truststore.
keytool -keystore /tmp/truststore.p12 -storetype pkcs12 -alias my-cluster-kafka -storepass $STOREPASS -import -file /tmp/my-cluster-kafka-ca.crt -noprompt
Keep the session open to check authorized access.
Check the authorization rules applied through the Keycloak realm using an interactive CLI session.
Apply the checks using Kafka’s example producer and consumer clients to create topics with user and service accounts that have different levels of access.
Use the team-a-client
and team-b-client
clients to check the authorization rules.
Use the alice
admin user to perform additional administrative tasks on Kafka.
The Kafka image used in this example contains Kafka producer and consumer binaries.
Setting up client and admin user configuration
-
Prepare a Kafka configuration file with authentication properties for the team-a-client
client.
SSO_HOST=SSO-HOSTNAME
cat > /tmp/team-a-client.properties << EOF
security.protocol=SASL_SSL
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.mechanism=OAUTHBEARER
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.client.id="team-a-client" \
oauth.client.secret="team-a-client-secret" \
oauth.ssl.truststore.location="/tmp/truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.token.endpoint.uri="https://$SSO_HOST/realms/kafka-authz/protocol/openid-connect/token" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
EOF
The SASL OAUTHBEARER
mechanism is used.
This mechanism requires a client ID and client secret, which means the client first connects to the Keycloak server to obtain an access token.
The client then connects to the Kafka broker and uses the access token to authenticate.
-
Prepare a Kafka configuration file with authentication properties for the team-b-client
client.
cat > /tmp/team-b-client.properties << EOF
security.protocol=SASL_SSL
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.mechanism=OAUTHBEARER
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.client.id="team-b-client" \
oauth.client.secret="team-b-client-secret" \
oauth.ssl.truststore.location="/tmp/truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.token.endpoint.uri="https://$SSO_HOST/realms/kafka-authz/protocol/openid-connect/token" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
EOF
-
Authenticate admin user alice
by using curl
and performing a password grant authentication to obtain a refresh token.
USERNAME=alice
PASSWORD=alice-password
GRANT_RESPONSE=$(curl -X POST "https://$SSO_HOST/realms/kafka-authz/protocol/openid-connect/token" -H 'Content-Type: application/x-www-form-urlencoded' -d "grant_type=password&username=$USERNAME&password=$PASSWORD&client_id=kafka-cli&scope=offline_access" -s -k)
REFRESH_TOKEN=$(echo $GRANT_RESPONSE | awk -F "refresh_token\":\"" '{printf $2}' | awk -F "\"" '{printf $1}')
The refresh token is an offline token that is long-lived and does not expire.
-
Prepare a Kafka configuration file with authentication properties for the admin user alice
.
cat > /tmp/alice.properties << EOF
security.protocol=SASL_SSL
ssl.truststore.location=/tmp/truststore.p12
ssl.truststore.password=$STOREPASS
ssl.truststore.type=PKCS12
sasl.mechanism=OAUTHBEARER
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.refresh.token="$REFRESH_TOKEN" \
oauth.client.id="kafka-cli" \
oauth.ssl.truststore.location="/tmp/truststore.p12" \
oauth.ssl.truststore.password="$STOREPASS" \
oauth.ssl.truststore.type="PKCS12" \
oauth.token.endpoint.uri="https://$SSO_HOST/realms/kafka-authz/protocol/openid-connect/token" ;
sasl.login.callback.handler.class=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler
EOF
The kafka-cli
public client is used for the oauth.client.id
in the sasl.jaas.config
.
Since it’s a public client it does not require a secret.
The client authenticates with the refresh token that was authenticated in the previous step.
The refresh token requests an access token behind the scenes, which is then sent to the Kafka broker for authentication.
Producing messages with authorized access
Use the team-a-client
configuration to check that you can produce messages to topics that start with a_
or x_
.
-
Write to topic my-topic
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic my-topic \
--producer.config=/tmp/team-a-client.properties
First message
This request returns a Not authorized to access topics: [my-topic]
error.
team-a-client
has a Dev Team A
role that gives it permission to perform any supported actions on topics that start with a_
, but can only write to topics that start with x_
.
The topic named my-topic
matches neither of those rules.
-
Write to topic a_messages
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic a_messages \
--producer.config /tmp/team-a-client.properties
First message
Second message
Messages are produced to Kafka successfully.
-
Press CTRL+C to exit the CLI application.
-
Check the Kafka container log for a debug log of Authorization GRANTED
for the request.
kubectl logs my-cluster-kafka-0 -f -n $NS
Consuming messages with authorized access
Use the team-a-client
configuration to consume messages from topic a_messages
.
-
Fetch messages from topic a_messages
.
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic a_messages \
--from-beginning --consumer.config /tmp/team-a-client.properties
The request returns an error because the Dev Team A
role for team-a-client
only has access to consumer groups that have names starting with a_
.
-
Update the team-a-client
properties to specify the custom consumer group it is permitted to use.
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic a_messages \
--from-beginning --consumer.config /tmp/team-a-client.properties --group a_consumer_group_1
The consumer receives all the messages from the a_messages
topic.
Administering Kafka with authorized access
The team-a-client
is an account without any cluster-level access, but it can be used with some administrative operations.
-
List topics.
bin/kafka-topics.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/team-a-client.properties --list
The a_messages
topic is returned.
-
List consumer groups.
bin/kafka-consumer-groups.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/team-a-client.properties --list
The a_consumer_group_1
consumer group is returned.
Fetch details on the cluster configuration.
bin/kafka-configs.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/team-a-client.properties \
--entity-type brokers --describe --entity-default
The request returns an error because the operation requires cluster level permissions that team-a-client
does not have.
Using clients with different permissions
Use the team-b-client
configuration to produce messages to topics that start with b_
.
-
Write to topic a_messages
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic a_messages \
--producer.config /tmp/team-b-client.properties
Message 1
This request returns a Not authorized to access topics: [a_messages]
error.
-
Write to topic b_messages
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic b_messages \
--producer.config /tmp/team-b-client.properties
Message 1
Message 2
Message 3
Messages are produced to Kafka successfully.
-
Write to topic x_messages
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--producer.config /tmp/team-b-client.properties
Message 1
A Not authorized to access topics: [x_messages]
error is returned,
The team-b-client
can only read from topic x_messages
.
-
Write to topic x_messages
using team-a-client
.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--producer.config /tmp/team-a-client.properties
Message 1
This request returns a Not authorized to access topics: [x_messages]
error.
The team-a-client
can write to the x_messages
topic, but it does not have a permission to create a topic if it does not yet exist.
Before team-a-client
can write to the x_messages
topic, an admin power user must create it with the correct configuration, such as the number of partitions and replicas.
Managing Kafka with an authorized admin user
Use admin user alice
to manage Kafka.
alice
has full access to manage everything on any Kafka cluster.
-
Create the x_messages
topic as alice
.
bin/kafka-topics.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/alice.properties \
--topic x_messages --create --replication-factor 1 --partitions 1
The topic is created successfully.
-
List all topics as alice
.
bin/kafka-topics.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/alice.properties --list
bin/kafka-topics.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/team-a-client.properties --list
bin/kafka-topics.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/team-b-client.properties --list
Admin user alice
can list all the topics, whereas team-a-client
and team-b-client
can only list the topics they have access to.
The Dev Team A
and Dev Team B
roles both have Describe
permission on topics that start with x_
, but they cannot see the other team’s topics because they do not have Describe
permissions on them.
-
Use the team-a-client
to produce messages to the x_messages
topic:
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--producer.config /tmp/team-a-client.properties
Message 1
Message 2
Message 3
As alice
created the x_messages
topic, messages are produced to Kafka successfully.
-
Use the team-b-client
to produce messages to the x_messages
topic.
bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--producer.config /tmp/team-b-client.properties
Message 4
Message 5
This request returns a Not authorized to access topics: [x_messages]
error.
-
Use the team-b-client
to consume messages from the x_messages
topic:
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--from-beginning --consumer.config /tmp/team-b-client.properties --group x_consumer_group_b
The consumer receives all the messages from the x_messages
topic.
-
Use the team-a-client
to consume messages from the x_messages
topic.
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--from-beginning --consumer.config /tmp/team-a-client.properties --group x_consumer_group_a
This request returns a Not authorized to access topics: [x_messages]
error.
-
Use the team-a-client
to consume messages from a consumer group that begins with a_
.
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--from-beginning --consumer.config /tmp/team-a-client.properties --group a_consumer_group_a
This request returns a Not authorized to access topics: [x_messages]
error.
Dev Team A
has no Read
access on topics that start with a x_
.
-
Use alice
to produce messages to the x_messages
topic.
bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --topic x_messages \
--from-beginning --consumer.config /tmp/alice.properties
Messages are produced to Kafka successfully.
alice
can read from or write to any topic.
-
Use alice
to read the cluster configuration.
bin/kafka-configs.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 --command-config /tmp/alice.properties \
--entity-type brokers --describe --entity-default
The cluster configuration for this example is empty.
Strimzi supports TLS for encrypted communication between Kafka and Strimzi components.
Strimzi establishes encrypted TLS connections for communication between the following components when using Kafka in KRaft mode:
-
Kafka brokers
-
Kafka controllers
-
Kafka brokers and controllers
-
Strimzi operators and Kafka
-
Cruise Control and Kafka brokers
-
Kafka Exporter and Kafka brokers
Connections between clients and Kafka brokers use listeners that you must configure to use TLS-encrypted communication.
You configure these listeners in the Kafka
custom resource and each listener name and port number must be unique within the cluster.
Communication between Kafka brokers and Kafka clients is encrypted according to how the tls
property is configured for the listener.
For more information, see Setting up client access to a Kafka cluster.
The following diagram shows the connections for secure communication.
Figure 6. KRaft-based Kafka communication secured by TLS encryption
The ports shown in the diagram are used as follows:
- Control plane listener (9090)
-
The internal control plane listener on port 9090 facilitates interbroker communication between Kafka controllers and broker-to-controller communication.
Additionally, the Cluster Operator communicates with the controllers through the listener.
This listener is not accessible to Kafka clients.
- Replication listener (9091)
-
Data replication between brokers, as well as internal connections to the brokers from Strimzi operators, Cruise Control, and the Kafka Exporter, use the replication listener on port 9091.
This listener is not accessible to Kafka clients.
- Listeners for client connections (9092 or higher)
-
For TLS-encrypted communication (through configuration of the listener), internal and external clients connect to Kafka brokers.
External clients (producers and consumers) connect to the Kafka brokers through the advertised listener port.
Important
|
When configuring listeners for client access to brokers, you can use port 9092 or higher (9093, 9094, and so on), but with a few exceptions.
The listeners cannot be configured to use the ports reserved for interbroker communication (9090 and 9091), Prometheus metrics (9404), and JMX (Java Management Extensions) monitoring (9999).
|
If you are using ZooKeeper for cluster management, there are TLS connections between ZooKeeper and Kafka brokers and Strimzi operators.
The following diagram shows the connections for secure communication when using ZooKeeper.
Figure 7. Kafka and ZooKeeper communication secured by TLS encryption
The ZooKeeper ports are used as follows:
- ZooKeeper Port (2181)
-
ZooKeeper port for connection to Kafka brokers.
Additionally, the Cluster Operator communicates with ZooKeeper through this port.
- ZooKeeper internodal communication port (2888)
-
ZooKeeper port for internodal communication between ZooKeeper nodes.
- ZooKeeper leader election port (3888)
-
ZooKeeper port for leader election among ZooKeeper nodes in a ZooKeeper cluster.
To support encryption, each Strimzi component needs its own private keys and public key certificates.
All component certificates are signed by an internal CA (certificate authority) called the cluster CA.
CA (Certificate Authority) certificates are generated by the Cluster Operator to verify the identities of components and clients.
Similarly, each Kafka client application connecting to Strimzi using mTLS needs to use private keys and certificates.
A second internal CA, named the clients CA, is used to sign certificates for the Kafka clients.
Both the cluster CA and clients CA have a self-signed public key certificate.
Kafka brokers are configured to trust certificates signed by either the cluster CA or clients CA.
Components that clients do not need to connect to, such as ZooKeeper, only trust certificates signed by the cluster CA.
Unless TLS encryption for external listeners is disabled, client applications must trust certificates signed by the cluster CA.
This is also true for client applications that perform mTLS authentication.
By default, Strimzi automatically generates and renews CA certificates issued by the cluster CA or clients CA.
You can configure the management of these CA certificates using Kafka.spec.clusterCa
and Kafka.spec.clientsCa
properties.
The Cluster Operator automatically sets up and renews TLS certificates to enable encryption and authentication within a cluster.
It also sets up other TLS certificates if you want to enable encryption or mTLS authentication between Kafka brokers and clients.
Secrets are created when custom resources are deployed, such as Kafka
and KafkaUser
.
Strimzi uses these secrets to store private and public key certificates for Kafka clusters, clients, and users.
The secrets are used for establishing TLS encrypted connections between Kafka brokers, and between brokers and clients.
They are also used for mTLS authentication.
Cluster and clients secrets are always pairs: one contains the public key and one contains the private key.
- Cluster secret
-
A cluster secret contains the cluster CA to sign Kafka broker certificates.
Connecting clients use the certificate to establish a TLS encrypted connection with a Kafka cluster. The certificate verifies broker identity.
- Client secret
-
A client secret contains the clients CA for a user to sign its own client certificate.
This allows mutual authentication against the Kafka cluster. The broker validates a client’s identity through the certificate.
- User secret
-
A user secret contains a private key and certificate. The secret is created and signed by the clients CA when a new user is created. The key and certificate are used to authenticate and authorize the user when accessing the cluster.
Note
|
You can provide Kafka listener certificates for TLS listeners or external listeners that have TLS encryption enabled.
Use Kafka listener certificates to incorporate the security infrastructure you already have in place.
|
The secrets created by Strimzi provide private keys and certificates in PEM (Privacy Enhanced Mail) and PKCS #12 (Public-Key Cryptography Standards) formats.
PEM and PKCS #12 are OpenSSL-generated key formats for TLS communications using the SSL protocol.
You can configure mutual TLS (mTLS) authentication that uses the credentials contained in the secrets generated for a Kafka cluster and user.
To set up mTLS, you must first do the following:
When you deploy a Kafka cluster, a <cluster_name>-cluster-ca-cert
secret is created with public key to verify the cluster.
You use the public key to configure a truststore for the client.
When you create a KafkaUser
, a <kafka_user_name>
secret is created with the keys and certificates to verify the user (client).
Use these credentials to configure a keystore for the client.
With the Kafka cluster and client set up to use mTLS, you extract credentials from the secrets and add them to your client configuration.
- PEM keys and certificates
-
For PEM, you add the following to your client configuration:
- Truststore
-
- Keystore
-
-
user.crt
from the <kafka_user_name>
secret, which is the public certificate of the user.
-
user.key
from the <kafka_user_name>
secret, which is the private key of the user.
- PKCS #12 keys and certificates
-
For PKCS #12, you add the following to your client configuration:
- Truststore
-
-
ca.p12
from the <cluster_name>-cluster-ca-cert
secret, which is the CA certificate for the cluster.
-
ca.password
from the <cluster_name>-cluster-ca-cert
secret, which is the password to access the public cluster CA certificate.
- Keystore
-
-
user.p12
from the <kafka_user_name>
secret, which is the public key certificate of the user.
-
user.password
from the <kafka_user_name>
secret, which is the password to access the public key certificate of the Kafka user.
PKCS #12 is supported by Java, so you can add the values of the certificates directly to your Java client configuration.
You can also reference the certificates from a secure storage location.
With PEM files, you must add the certificates directly to the client configuration in single-line format.
Choose a format that’s suitable for establishing TLS connections between your Kafka cluster and client.
Use PKCS #12 if you are unfamiliar with PEM.
Note
|
All keys are 2048 bits in size and, by default, are valid for 365 days from the initial generation.
You can change the validity period.
|
The Cluster Operator generates the following certificates, which are saved as secrets in the Kubernetes cluster.
Strimzi uses these secrets by default.
The cluster CA and clients CA have separate secrets for the private key and public key.
<cluster_name>-cluster-ca
-
Contains the private key of the cluster CA. Strimzi and Kafka components use the private key to sign server certificates.
<cluster_name>-cluster-ca-cert
-
Contains the public key of the cluster CA. Kafka clients use the public key to verify the identity of the Kafka brokers they are connecting to with TLS server authentication.
<cluster_name>-clients-ca
-
Contains the private key of the clients CA. Kafka clients use the private key to sign new user certificates for mTLS authentication when connecting to Kafka brokers.
<cluster_name>-clients-ca-cert
-
Contains the public key of the clients CA. Kafka brokers use the public key to verify the identity of clients accessing the Kafka brokers when mTLS authentication is used.
Secrets for communication between Strimzi components contain a private key and a public key certificate signed by the cluster CA.
<cluster_name>-kafka-brokers
-
Contains the private and public keys for Kafka brokers.
<cluster_name>-zookeeper-nodes
-
Contains the private and public keys for ZooKeeper nodes.
<cluster_name>-cluster-operator-certs
-
Contains the private and public keys for encrypting communication between the Cluster Operator and Kafka or ZooKeeper.
<cluster_name>-entity-topic-operator-certs
-
Contains the private and public keys for encrypting communication between the Topic Operator and Kafka or ZooKeeper.
<cluster_name>-entity-user-operator-certs
-
Contains the private and public keys for encrypting communication between the User Operator and Kafka or ZooKeeper.
<cluster_name>-cruise-control-certs
-
Contains the private and public keys for encrypting communication between Cruise Control and Kafka or ZooKeeper.
<cluster_name>-kafka-exporter-certs
-
Contains the private and public keys for encrypting communication between Kafka Exporter and Kafka or ZooKeeper.
Cluster CA secrets are managed by the Cluster Operator in a Kafka cluster.
Only the <cluster_name>-cluster-ca-cert
secret is required by clients.
All other cluster secrets are accessed by Strimzi components.
You can enforce this using Kubernetes role-based access controls, if necessary.
Note
|
The CA certificates in <cluster_name>-cluster-ca-cert must be trusted by Kafka client applications so that they validate the Kafka broker certificates when connecting to Kafka brokers over TLS.
|
Table 20. Fields in the <cluster_name>-cluster-ca
secret
Field |
Description |
ca.key
|
The current private key for the cluster CA. |
Table 21. Fields in the <cluster_name>-cluster-ca-cert
secret
Field |
Description |
ca.p12
|
PKCS #12 store for storing certificates and keys. |
ca.password
|
Password for protecting the PKCS #12 store. |
ca.crt
|
The current certificate for the cluster CA. |
Table 22. Fields in the <cluster_name>-kafka-brokers
secret
Field |
Description |
<cluster_name>-kafka-<num>.p12
|
PKCS #12 store for storing certificates and keys. |
<cluster_name>-kafka-<num>.password
|
Password for protecting the PKCS #12 store. |
<cluster_name>-kafka-<num>.crt
|
Certificate for a Kafka broker pod <num>. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
<cluster_name>-kafka-<num>.key
|
Private key for a Kafka broker pod <num> . |
Table 23. Fields in the <cluster_name>-zookeeper-nodes
secret
Field |
Description |
<cluster_name>-zookeeper-<num>.p12
|
PKCS #12 store for storing certificates and keys. |
<cluster_name>-zookeeper-<num>.password
|
Password for protecting the PKCS #12 store. |
<cluster_name>-zookeeper-<num>.crt
|
Certificate for ZooKeeper node <num>. Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
<cluster_name>-zookeeper-<num>.key
|
Private key for ZooKeeper pod <num> . |
Table 24. Fields in the <cluster_name>-cluster-operator-certs
secret
Field |
Description |
cluster-operator.p12
|
PKCS #12 store for storing certificates and keys. |
cluster-operator.password
|
Password for protecting the PKCS #12 store. |
cluster-operator.crt
|
Certificate for mTLS communication between the Cluster Operator and Kafka or ZooKeeper.
Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
cluster-operator.key
|
Private key for mTLS communication between the Cluster Operator and Kafka or ZooKeeper. |
Table 25. Fields in the <cluster_name>-entity-topic-operator-certs
secret
Field |
Description |
entity-operator.p12
|
PKCS #12 store for storing certificates and keys. |
entity-operator.password
|
Password for protecting the PKCS #12 store. |
entity-operator.crt
|
Certificate for mTLS communication between the Topic Operator and Kafka or ZooKeeper.
Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
entity-operator.key
|
Private key for mTLS communication between the Topic Operator and Kafka or ZooKeeper. |
Table 26. Fields in the <cluster_name>-entity-user-operator-certs
secret
Field |
Description |
entity-operator.p12
|
PKCS #12 store for storing certificates and keys. |
entity-operator.password
|
Password for protecting the PKCS #12 store. |
entity-operator.crt
|
Certificate for mTLS communication between the User Operator and Kafka or ZooKeeper.
Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
entity-operator.key
|
Private key for mTLS communication between the User Operator and Kafka or ZooKeeper. |
Table 27. Fields in the <cluster_name>-cruise-control-certs
secret
Field |
Description |
cruise-control.p12
|
PKCS #12 store for storing certificates and keys. |
cruise-control.password
|
Password for protecting the PKCS #12 store. |
cruise-control.crt
|
Certificate for mTLS communication between Cruise Control and Kafka or ZooKeeper.
Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
cruise-control.key
|
Private key for mTLS communication between the Cruise Control and Kafka or ZooKeeper. |
Table 28. Fields in the <cluster_name>-kafka-exporter-certs
secret
Field |
Description |
kafka-exporter.p12
|
PKCS #12 store for storing certificates and keys. |
kafka-exporter.password
|
Password for protecting the PKCS #12 store. |
kafka-exporter.crt
|
Certificate for mTLS communication between Kafka Exporter and Kafka or ZooKeeper.
Signed by a current or former cluster CA private key in <cluster_name>-cluster-ca . |
kafka-exporter.key
|
Private key for mTLS communication between the Kafka Exporter and Kafka or ZooKeeper. |
Clients CA secrets are managed by the Cluster Operator in a Kafka cluster.
The certificates in <cluster_name>-clients-ca-cert
are those which the Kafka brokers trust.
The <cluster_name>-clients-ca
secret is used to sign the certificates of client applications.
This secret must be accessible to the Strimzi components and for administrative access if you are intending to issue application certificates without using the User Operator.
You can enforce this using Kubernetes role-based access controls, if necessary.
Table 29. Fields in the <cluster_name>-clients-ca
secret
Field |
Description |
ca.key
|
The current private key for the clients CA. |
Table 30. Fields in the <cluster_name>-clients-ca-cert
secret
Field |
Description |
ca.p12
|
PKCS #12 store for storing certificates and keys. |
ca.password
|
Password for protecting the PKCS #12 store. |
ca.crt
|
The current certificate for the clients CA. |
User secrets are managed by the User Operator.
When a user is created using the User Operator, a secret is generated using the name of the user.
Table 31. Fields in the user_name
secret
Secret name |
Field within secret |
Description |
<user_name>
|
user.p12
|
PKCS #12 store for storing certificates and keys. |
user.password
|
Password for protecting the PKCS #12 store. |
user.crt
|
Certificate for the user, signed by the clients CA |
user.key
|
Private key for the user |
By configuring the clusterCaCert
template property in the Kafka
custom resource, you can add custom labels and annotations to the Cluster CA secrets created by the Cluster Operator.
Labels and annotations are useful for identifying objects and adding contextual information.
You configure template properties in Strimzi custom resources.
Example template customization to add labels and annotations to secrets
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
template:
clusterCaCert:
metadata:
labels:
label1: value1
label2: value2
annotations:
annotation1: value1
annotation2: value2
# ...
By default, the cluster and clients CA secrets are created with an ownerReference
property that is set to the Kafka
custom resource.
This means that, when the Kafka
custom resource is deleted, the CA secrets are also deleted (garbage collected) by Kubernetes.
If you want to reuse the CA for a new cluster, you can disable the ownerReference
by setting the generateSecretOwnerReference
property for the cluster and clients CA secrets to false
in the Kafka
configuration.
When the ownerReference
is disabled, CA secrets are not deleted by Kubernetes when the corresponding Kafka
custom resource is deleted.
Example Kafka configuration with disabled ownerReference
for cluster and clients CAs
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
# ...
spec:
# ...
clusterCa:
generateSecretOwnerReference: false
clientsCa:
generateSecretOwnerReference: false
# ...
Cluster CA and clients CA certificates are only valid for a limited time period, known as the validity period.
This is usually defined as a number of days since the certificate was generated.
For CA certificates automatically created by the Cluster Operator, configure the validity period for certificates in the kafka
resource using the following properties:
The default validity period for both certificates is 365 days.
Manually-installed CA certificates should have their own validity periods defined.
When a CA certificate expires, components and clients that still trust that certificate do not accept connections from peers whose certificates were signed by the CA private key.
The components and clients need to trust the new CA certificate instead.
To allow the renewal of CA certificates without a loss of service, the Cluster Operator initiates certificate renewal before the old CA certificates expire.
Configure the renewal period of the certificates created by the Cluster Operator in the kafka
resource using the following properties:
The default renewal period for both certificates is 30 days.
The renewal period is measured backwards, from the expiry date of the current certificate.
Validity period against renewal period
Not Before Not After
| |
|<--------------- validityDays --------------->|
<--- renewalDays --->|
To make a change to the validity and renewal periods after creating the Kafka cluster, configure and apply the Kafka
custom resource,
and manually renew the CA certificates.
If you do not manually renew the certificates, the new periods will be used the next time the certificate is renewed automatically.
Example Kafka configuration for certificate validity and renewal periods
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
# ...
spec:
# ...
clusterCa:
renewalDays: 30
validityDays: 365
generateCertificateAuthority: true
clientsCa:
renewalDays: 30
validityDays: 365
generateCertificateAuthority: true
# ...
The behavior of the Cluster Operator during the renewal period depends on the settings for the generateCertificateAuthority
certificate generation properties for the cluster CA and clients CA.
true
-
If the properties are set to true
, a CA certificate is generated automatically by the Cluster Operator, and renewed automatically within the renewal period.
false
-
If the properties are set to false
, a CA certificate is not generated by the Cluster Operator. Use this option if you are installing your own certificates.
When it’s time to renew CA certificates, the Cluster Operator follows these steps:
-
Generates a new CA certificate, but retains the existing key.
The new certificate replaces the old one with the name ca.crt
within the corresponding Secret
.
-
Generates new client certificates (for ZooKeeper nodes, Kafka brokers, and the Entity Operator).
This is not strictly necessary because the signing key has not changed, but it keeps the validity period of the client certificate in sync with the CA certificate.
-
Restarts ZooKeeper nodes to trust the new CA certificate and use the new client certificates.
-
Restarts Kafka brokers to trust the new CA certificate and use the new client certificates.
-
Restarts the Topic Operator and User Operator to trust the new CA certificate and use the new client certificates.
User certificates are signed by the clients CA.
The User Operator handles renewing user certificates when the client’s CA is renewed.
The Cluster Operator is not aware of the client applications using the Kafka cluster.
You must ensure clients continue to work after certificate renewal.
The renewal process depends on how the clients are configured.
When connecting to the cluster, and to ensure they operate correctly, client applications must include the following configuration:
-
Truststore credentials from the <cluster_name>-cluster-ca-cert
secret to verify the identity of the Kafka cluster.
-
Keystore credentials from the <user_name>
secret to connect to verify the user when connecting to the Kafka cluster.
The user secret provides credentials in PEM and PKCS #12 format, or it can provide a password when using SCRAM-SHA authentication.
The User Operator creates the user credentials when a user is created.
For an example of adding certificates to client configuration, see Securing user access to Kafka.
If you are provisioning client certificates and keys manually, you must generate new client certificates and ensure the new certificates are used by clients within the renewal period.
Failure to do this by the end of the renewal period could result in client applications being unable to connect to the cluster.
Note
|
For workloads running inside the same Kubernetes cluster and namespace, secrets can be mounted as a volume so the client pods construct their keystores and truststores from the current state of the secrets.
For more details on this procedure, see Configuring internal clients to trust the cluster CA.
|
Updates are usually triggered by changes to the Kafka
resource by the user or through user tooling.
Rolling restarts for certificate expiration may occur without Kafka
resource changes.
While unscheduled restarts shouldn’t affect service availability, they could impact the performance of client applications.
Maintenance time windows allow scheduling of these updates for convenient times.
Configure maintenance time windows as follows:
The following example configures a single maintenance time window that starts at midnight and ends at 01:59am (UTC), on Sundays, Mondays, Tuesdays, Wednesdays, and Thursdays.
Example maintenance time window configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
#...
maintenanceTimeWindows:
- "* * 0-1 ? * SUN,MON,TUE,WED,THU *"
#...
Note
|
The Cluster Operator doesn’t adhere strictly to the given time windows for maintenance operations.
Maintenance operations are triggered by the first reconciliation that occurs within the specified time window.
If the time window is shorter than the interval between reconciliations, there’s a risk that the reconciliation may happen outside of the time window,
Therefore, maintenance time windows must be at least as long as the interval between reconciliations.
|
Cluster and clients CA certificates generated by the Cluster Operator auto-renew at the start of their respective certificate renewal periods.
However, you can use the strimzi.io/force-renew
annotation to manually renew one or both of these certificates before the certificate renewal period starts.
You might do this for security reasons, or if you have changed the renewal or validity periods for the certificates.
A renewed certificate uses the same private key as the old certificate.
Prerequisites
-
The Cluster Operator must be deployed.
-
A Kafka cluster in which CA certificates and private keys are installed.
-
The OpenSSL TLS management tool to check the period of validity for CA certificates.
In this procedure, we use a Kafka cluster named my-cluster
within the my-project
namespace.
Procedure
-
Apply the strimzi.io/force-renew
annotation to the secret that contains the CA certificate that you want to renew.
Renewing the Cluster CA secret
kubectl annotate secret my-cluster-cluster-ca-cert -n my-project strimzi.io/force-renew="true"
Renewing the Clients CA secret
kubectl annotate secret my-cluster-clients-ca-cert -n my-project strimzi.io/force-renew="true"
-
At the next reconciliation, the Cluster Operator generates new certificates.
If maintenance time windows are configured, the Cluster Operator generates the new CA certificate at the first reconciliation within the next maintenance time window.
-
Check the period of validity for the new CA certificates.
Checking the period of validity for the new cluster CA certificate
kubectl get secret my-cluster-cluster-ca-cert -n my-project -o=jsonpath='{.data.ca\.crt}' | base64 -d | openssl x509 -noout -dates
Checking the period of validity for the new clients CA certificate
kubectl get secret my-cluster-clients-ca-cert -n my-project -o=jsonpath='{.data.ca\.crt}' | base64 -d | openssl x509 -noout -dates
The command returns a notBefore
and notAfter
date, which is the valid start and end date for the CA certificate.
-
Update client configurations to trust the new cluster CA certificate.
The Cluster Operator automatically renews the cluster and clients CA certificates when their renewal periods begin.
Nevertheless, unexpected operational problems or disruptions may prevent the renewal process, such as prolonged downtime of the Cluster Operator or unavailability of the Kafka cluster.
If CA certificates expire, Kafka cluster components cannot communicate with each other and the Cluster Operator cannot renew the CA certificates without manual intervention.
To promptly perform a recovery, follow the steps outlined in this procedure in the order given.
You can recover from expired cluster and clients CA certificates.
The process involves deleting the secrets containing the expired certificates so that new ones are generated by the Cluster Operator.
For more information on the secrets managed in Strimzi, see Secrets generated by the Cluster Operator.
Note
|
If you are using your own CA certificates and they expire, the process is similar, but you need to renew the CA certificates rather than use certificates generated by the Cluster Operator.
|
Prerequisites
-
The Cluster Operator must be deployed.
-
A Kafka cluster in which CA certificates and private keys are installed.
-
The OpenSSL TLS management tool to check the period of validity for CA certificates.
In this procedure, we use a Kafka cluster named my-cluster
within the my-project
namespace.
Procedure
-
Delete the secret containing the expired CA certificate.
Deleting the Cluster CA secret
kubectl delete secret my-cluster-cluster-ca-cert -n my-project
Deleting the Clients CA secret
kubectl delete secret my-cluster-clients-ca-cert -n my-project
-
Wait for the Cluster Operator to generate new certificates.
-
A new CA cluster certificate to verify the identity of the Kafka brokers is created in a secret of the same name (my-cluster-cluster-ca-cert
).
-
A new CA clients certificate to verify the identity of Kafka users is created in a secret of the same name (my-cluster-clients-ca-cert
).
-
Check the period of validity for the new CA certificates.
Checking the period of validity for the new cluster CA certificate
kubectl get secret my-cluster-cluster-ca-cert -n my-project -o=jsonpath='{.data.ca\.crt}' | base64 -d | openssl x509 -noout -dates
Checking the period of validity for the new clients CA certificate
kubectl get secret my-cluster-clients-ca-cert -n my-project -o=jsonpath='{.data.ca\.crt}' | base64 -d | openssl x509 -noout -dates
The command returns a notBefore
and notAfter
date, which is the valid start and end date for the CA certificate.
-
Delete the component pods and secrets that use the CA certificates.
-
Delete the ZooKeeper secret.
-
Wait for the Cluster Operator to detect the missing ZooKeeper secret and recreate it.
-
Delete all ZooKeeper pods.
-
Delete the Kafka secret.
-
Wait for the Cluster Operator to detect the missing Kafka secret and recreate it.
-
Delete all Kafka pods.
If you are only recovering the clients CA certificate, you only need to delete the Kafka secret and pods.
You can use the following kubectl
command to find resources and also verify that they have been removed.
kubectl get <resource_type> --all-namespaces | grep <kafka_cluster_name>
Replace <resource_type>
with the type of the resource, such as Pod
or Secret
.
-
Wait for the Cluster Operator to detect the missing Kafka and ZooKeeper pods and recreate them with the updated CA certificates.
On reconciliation, the Cluster Operator automatically updates other components to trust the new CA certificates.
-
Verify that there are no issues related to certificate validation in the Cluster Operator log.
-
Update client configurations to trust the new cluster CA certificate.
You can replace the private keys used by the cluster CA and clients CA certificates generated by the Cluster Operator.
When a private key is replaced, the Cluster Operator generates a new CA certificate for the new private key.
At the next reconciliation the Cluster Operator will:
If maintenance time windows are configured, the Cluster Operator will generate the new private key and CA certificate at the first reconciliation within the next maintenance time window.
Client applications must reload the cluster and clients CA certificates that were renewed by the Cluster Operator.
This procedure describes how to configure a Kafka client that resides inside the Kubernetes cluster — connecting to a TLS listener — to trust the cluster CA certificate.
The easiest way to achieve this for an internal client is to use a volume mount to access the Secrets
containing the necessary certificates and keys.
Follow the steps to configure trust certificates that are signed by the cluster CA for Java-based Kafka Producer, Consumer, and Streams APIs.
Choose the steps to follow according to the certificate format of the cluster CA: PKCS #12 (.p12
) or PEM (.crt
).
The steps describe how to mount the Cluster Secret that verifies the identity of the Kafka cluster to the client pod.
Prerequisites
-
The Cluster Operator must be running.
-
There needs to be a Kafka
resource within the Kubernetes cluster.
-
You need a Kafka client application inside the Kubernetes cluster that will connect using TLS, and needs to trust the cluster CA certificate.
-
The client application must be running in the same namespace as the Kafka
resource.
Using PKCS #12 format (.p12)
-
Mount the cluster Secret as a volume when defining the client pod.
kind: Pod
apiVersion: v1
metadata:
name: client-pod
spec:
containers:
- name: client-name
image: client-name
volumeMounts:
- name: secret-volume
mountPath: /data/p12
env:
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: my-password
volumes:
- name: secret-volume
secret:
secretName: my-cluster-cluster-ca-cert
Here we’re mounting the following:
-
The PKCS #12 file into an exact path, which can be configured
-
The password into an environment variable, where it can be used for Java configuration
-
Configure the Kafka client with the following properties:
-
A security protocol option:
-
ssl.truststore.location
with the truststore location where the certificates were imported.
-
ssl.truststore.password
with the password for accessing the truststore.
-
ssl.truststore.type=PKCS12
to identify the truststore type.
Using PEM format (.crt)
-
Mount the cluster Secret as a volume when defining the client pod.
kind: Pod
apiVersion: v1
metadata:
name: client-pod
spec:
containers:
- name: client-name
image: client-name
volumeMounts:
- name: secret-volume
mountPath: /data/crt
volumes:
- name: secret-volume
secret:
secretName: my-cluster-cluster-ca-cert
-
Use the extracted certificate to configure a TLS connection in clients that use certificates in X.509 format.
This procedure describes how to configure a Kafka client that resides outside the Kubernetes cluster – connecting to an external
listener – to trust the cluster CA certificate.
Follow this procedure when setting up the client and during the renewal period, when the old clients CA certificate is replaced.
Follow the steps to configure trust certificates that are signed by the cluster CA for Java-based Kafka Producer, Consumer, and Streams APIs.
Choose the steps to follow according to the certificate format of the cluster CA: PKCS #12 (.p12
) or PEM (.crt
).
The steps describe how to obtain the certificate from the Cluster Secret that verifies the identity of the Kafka cluster.
Important
|
The <cluster_name>-cluster-ca-cert secret contains more than one CA certificate during the CA certificate renewal period.
Clients must add all of them to their truststores.
|
Prerequisites
-
The Cluster Operator must be running.
-
There needs to be a Kafka
resource within the Kubernetes cluster.
-
You need a Kafka client application outside the Kubernetes cluster that will connect using TLS, and needs to trust the cluster CA certificate.
Using PKCS #12 format (.p12)
-
Extract the cluster CA certificate and password from the <cluster_name>-cluster-ca-cert
Secret of the Kafka cluster.
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.p12}' | base64 -d > ca.p12
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 -d > ca.password
Replace <cluster_name> with the name of the Kafka cluster.
-
Configure the Kafka client with the following properties:
-
A security protocol option:
-
ssl.truststore.location
with the truststore location where the certificates were imported.
-
ssl.truststore.password
with the password for accessing the truststore. This property can be omitted if it is not needed by the truststore.
-
ssl.truststore.type=PKCS12
to identify the truststore type.
Using PEM format (.crt)
-
Extract the cluster CA certificate from the <cluster_name>-cluster-ca-cert
secret of the Kafka cluster.
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 -d > ca.crt
-
Use the extracted certificate to configure a TLS connection in clients that use certificates in X.509 format.
Install and use your own CA certificates and private keys instead of using the defaults generated by the Cluster Operator.
You can replace the cluster and clients CA certificates and private keys.
You can switch to using your own CA certificates and private keys in the following ways:
The steps to replace the default CA certificates and private keys after deploying a Kafka cluster are the same as those used to renew your own CA certificates and private keys.
If you use your own certificates, they won’t be renewed automatically.
You need to renew the CA certificates and private keys before they expire.
Install your own CA certificates and private keys instead of using the cluster and clients CA certificates and private keys generated by the Cluster Operator.
-
Cluster CA secrets
-
Clients CA secrets
To install your own certificates, use the same names.
Prerequisites
-
The Cluster Operator is running.
-
A Kafka cluster is not yet deployed.
-
Your own X.509 certificates and keys in PEM format for the cluster CA or clients CA.
-
If you want to use a cluster or clients CA which is not a Root CA, you have to include the whole chain in the certificate file.
The chain should be in the following order:
-
The cluster or clients CA
-
One or more intermediate CAs
-
The root CA
-
All CAs in the chain should be configured using the X509v3 Basic Constraints extension. Basic Constraints limit the path length of a certificate chain.
-
The OpenSSL TLS management tool for converting certificates.
Before you begin
The Cluster Operator generates keys and certificates in PEM (Privacy Enhanced Mail) and PKCS #12 (Public-Key Cryptography Standards) formats.
You can add your own certificates in either format.
Some applications cannot use PEM certificates and support only PKCS #12 certificates.
If you don’t have a cluster certificate in PKCS #12 format, use the OpenSSL TLS management tool to generate one from your ca.crt
file.
Example certificate generation command
openssl pkcs12 -export -in ca.crt -nokeys -out ca.p12 -password pass:<P12_password> -caname ca.crt
Replace <P12_password> with your own password.
Procedure
-
Create a new secret that contains the CA certificate.
Client secret creation with a certificate in PEM format only
kubectl create secret generic <cluster_name>-clients-ca-cert --from-file=ca.crt=ca.crt
Cluster secret creation with certificates in PEM and PKCS #12 format
kubectl create secret generic <cluster_name>-cluster-ca-cert \
--from-file=ca.crt=ca.crt \
--from-file=ca.p12=ca.p12 \
--from-literal=ca.password=P12-PASSWORD
Replace <cluster_name> with the name of your Kafka cluster.
-
Create a new secret that contains the private key.
kubectl create secret generic <ca_key_secret> --from-file=ca.key=ca.key
-
Label the secrets.
kubectl label secret <ca_certificate_secret> strimzi.io/kind=Kafka strimzi.io/cluster="<cluster_name>"
kubectl label secret <ca_key_secret> strimzi.io/kind=Kafka strimzi.io/cluster="<cluster_name>"
-
Annotate the secrets
kubectl annotate secret <ca_certificate_secret> strimzi.io/ca-cert-generation="<ca_certificate_generation>"
kubectl annotate secret <ca_key_secret> strimzi.io/ca-key-generation="<ca_key_generation>"
-
Annotation strimzi.io/ca-cert-generation="<ca_certificate_generation>"
defines the generation of a new CA certificate.
-
Annotation strimzi.io/ca-key-generation="<ca_key_generation>"
defines the generation of a new CA key.
Start from 0 (zero) as the incremental value (strimzi.io/ca-cert-generation=0
) for your own CA certificate. Set a higher incremental value when you renew the certificates.
-
Create the Kafka
resource for your cluster, configuring either the Kafka.spec.clusterCa
or the Kafka.spec.clientsCa
object to not use generated CAs.
Example fragment Kafka
resource configuring the cluster CA to use certificates you supply for yourself
kind: Kafka
version: kafka.strimzi.io/v1beta2
spec:
# ...
clusterCa:
generateCertificateAuthority: false
If you are using your own CA certificates, you need to renew them manually.
The Cluster Operator will not renew them automatically.
Renew the CA certificates in the renewal period before they expire.
The procedure describes the renewal of CA certificates in PEM format.
Procedure
-
Update the Secret
for the CA certificate.
Edit the existing secret to add the new CA certificate and update the certificate generation annotation value.
kubectl edit secret <ca_certificate_secret_name>
<ca_certificate_secret_name> is the name of the Secret
, which is <kafka_cluster_name>-cluster-ca-cert
for the cluster CA certificate and <kafka_cluster_name>-clients-ca-cert
for the clients CA certificate.
The following example shows a secret for a cluster CA certificate that’s associated with a Kafka cluster named my-cluster
.
Example secret configuration for a cluster CA certificate
apiVersion: v1
kind: Secret
data:
ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... (1)
metadata:
annotations:
strimzi.io/ca-cert-generation: "0" (2)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca-cert
#...
type: Opaque
-
Current base64-encoded CA certificate
-
Current CA certificate generation annotation value
-
Encode your new CA certificate into base64.
cat <path_to_new_certificate> | base64
-
Update the CA certificate.
Copy the base64-encoded CA certificate from the previous step as the value for the ca.crt
property under data
.
-
Increase the value of the CA certificate generation annotation.
Update the strimzi.io/ca-cert-generation
annotation with a higher incremental value.
For example, change strimzi.io/ca-cert-generation=0
to strimzi.io/ca-cert-generation=1
.
If the Secret
is missing the annotation, the value is treated as 0
, so add the annotation with a value of 1
.
When Strimzi generates certificates, the certificate generation annotation is automatically incremented by the Cluster Operator.
For your own CA certificates, set the annotations with a higher incremental value.
The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates.
The strimzi.io/ca-cert-generation
has to be incremented on each CA certificate renewal.
-
Save the secret with the new CA certificate and certificate generation annotation value.
Example secret configuration updated with a new CA certificate
apiVersion: v1
kind: Secret
data:
ca.crt: GCa6LS3RTHeKFiFDGBOUDYFAZ0F... (1)
metadata:
annotations:
strimzi.io/ca-cert-generation: "1" (2)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca-cert
#...
type: Opaque
-
New base64-encoded CA certificate
-
New CA certificate generation annotation value
On the next reconciliation, the Cluster Operator performs a rolling update of ZooKeeper, Kafka, and other components to trust the new CA certificate.
If maintenance time windows are configured, the Cluster Operator will roll the pods at the first reconciliation within the next maintenance time window.
If you are using your own CA certificates and private keys, you need to renew them manually.
The Cluster Operator will not renew them automatically.
Renew the CA certificates in the renewal period before they expire.
You can also use the same procedure to replace the CA certificates and private keys generated by the Strimzi operators with your own.
Perform the steps in this procedure when you are renewing or replacing CA certificates and private keys.
If you are only renewing your own CA certificates, see Renewing your own CA certificates.
The procedure describes the renewal of CA certificates and private keys in PEM format.
Before going through the following steps, make sure that the CN (Common Name) of the new CA certificate is different from the current one.
For example, when the Cluster Operator renews certificates automatically it adds a v<version_number> suffix to identify a version.
Do the same with your own CA certificate by adding a different suffix on each renewal.
By using a different key to generate a new CA certificate, you retain the current CA certificate stored in the Secret
.
Procedure
-
Pause the reconciliation of the Kafka
custom resource.
-
Annotate the custom resource in Kubernetes, setting the pause-reconciliation
annotation to true
:
kubectl annotate Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation="true"
For example, for a Kafka
custom resource named my-cluster
:
kubectl annotate Kafka my-cluster strimzi.io/pause-reconciliation="true"
-
Check that the status conditions of the custom resource show a change to ReconciliationPaused
:
kubectl describe Kafka <name_of_custom_resource>
The type
condition changes to ReconciliationPaused
at the lastTransitionTime
.
-
Check the settings for the generateCertificateAuthority
properties in your Kafka
custom resource.
If a property is set to false
, a CA certificate is not generated by the Cluster Operator.
You require this setting if you are using your own certificates.
-
If needed, edit the existing Kafka
custom resource and set the generateCertificateAuthority
properties to false
.
kubectl edit Kafka <name_of_custom_resource>
The following example shows a Kafka
custom resource with both cluster and clients CA certificates generation delegated to the user.
Example Kafka
configuration using your own CA certificates
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
# ...
spec:
# ...
clusterCa:
generateCertificateAuthority: false # (1)
clientsCa:
generateCertificateAuthority: false # (2)
# ...
-
Use your own cluster CA
-
Use your own clients CA
-
Update the Secret
for the CA certificate.
-
Edit the existing secret to add the new CA certificate and update the certificate generation annotation value.
kubectl edit secret <ca_certificate_secret_name>
<ca_certificate_secret_name> is the name of the Secret
, which is <kafka_cluster_name>-cluster-ca-cert
for the cluster CA certificate and <kafka_cluster_name>-clients-ca-cert
for the clients CA certificate.
The following example shows a secret for a cluster CA certificate that’s associated with a Kafka cluster named my-cluster
.
Example secret configuration for a cluster CA certificate
apiVersion: v1
kind: Secret
data:
ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... # (1)
metadata:
annotations:
strimzi.io/ca-cert-generation: "0" # (2)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca-cert
#...
type: Opaque
-
Current base64-encoded CA certificate
-
Current CA certificate generation annotation value
-
Rename the current CA certificate to retain it.
Rename the current ca.crt
property under data
as ca-<date>.crt
, where <date> is the certificate expiry date in the format YEAR-MONTH-DAYTHOUR-MINUTE-SECONDZ.
For example ca-2023-01-26T17-32-00Z.crt:
.
Leave the value for the property as it is to retain the current CA certificate.
-
Encode your new CA certificate into base64.
cat <path_to_new_certificate> | base64
-
Update the CA certificate.
Create a new ca.crt
property under data
and copy the base64-encoded CA certificate from the previous step as the value for ca.crt
property.
-
Increase the value of the CA certificate generation annotation.
Update the strimzi.io/ca-cert-generation
annotation with a higher incremental value.
For example, change strimzi.io/ca-cert-generation=0
to strimzi.io/ca-cert-generation=1
.
If the Secret
is missing the annotation, the value is treated as 0
, so add the annotation with a value of 1
.
When Strimzi generates certificates, the certificate generation annotation is automatically incremented by the Cluster Operator.
For your own CA certificates, set the annotations with a higher incremental value.
The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates.
The strimzi.io/ca-cert-generation
has to be incremented on each CA certificate renewal.
-
Save the secret with the new CA certificate and certificate generation annotation value.
Example secret configuration updated with a new CA certificate
apiVersion: v1
kind: Secret
data:
ca.crt: GCa6LS3RTHeKFiFDGBOUDYFAZ0F... # (1)
ca-2023-01-26T17-32-00Z.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0F... # (2)
metadata:
annotations:
strimzi.io/ca-cert-generation: "1" # (3)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca-cert
#...
type: Opaque
-
New base64-encoded CA certificate
-
Old base64-encoded CA certificate
-
New CA certificate generation annotation value
-
Update the Secret
for the CA key used to sign your new CA certificate.
-
Edit the existing secret to add the new CA key and update the key generation annotation value.
kubectl edit secret <ca_key_name>
<ca_key_name> is the name of CA key, which is <kafka_cluster_name>-cluster-ca
for the cluster CA key and <kafka_cluster_name>-clients-ca
for the clients CA key.
The following example shows a secret for a cluster CA key that’s associated with a Kafka cluster named my-cluster
.
Example secret configuration for a cluster CA key
apiVersion: v1
kind: Secret
data:
ca.key: SA1cKF1GFDzOIiPOIUQBHDNFGDFS... # (1)
metadata:
annotations:
strimzi.io/ca-key-generation: "0" # (2)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca
#...
type: Opaque
-
Current base64-encoded CA key
-
Current CA key generation annotation value
-
Encode the CA key into base64.
cat <path_to_new_key> | base64
-
Update the CA key.
Copy the base64-encoded CA key from the previous step as the value for the ca.key
property under data
.
-
Increase the value of the CA key generation annotation.
Update the strimzi.io/ca-key-generation
annotation with a higher incremental value.
For example, change strimzi.io/ca-key-generation=0
to strimzi.io/ca-key-generation=1
.
If the Secret
is missing the annotation, it is treated as 0
, so add the annotation with a value of 1
.
When Strimzi generates certificates, the key generation annotation is automatically incremented by the Cluster Operator.
For your own CA certificates together with a new CA key, set the annotation with a higher incremental value.
The annotation needs a higher value than the one from the current secret so that the Cluster Operator can roll the pods and update the certificates and keys.
The strimzi.io/ca-key-generation
has to be incremented on each CA certificate renewal.
-
Save the secret with the new CA key and key generation annotation value.
Example secret configuration updated with a new CA key
apiVersion: v1
kind: Secret
data:
ca.key: AB0cKF1GFDzOIiPOIUQWERZJQ0F... # (1)
metadata:
annotations:
strimzi.io/ca-key-generation: "1" # (2)
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca
#...
type: Opaque
-
New base64-encoded CA key
-
New CA key generation annotation value
-
Resume from the pause.
To resume the Kafka
custom resource reconciliation, set the pause-reconciliation
annotation to false
.
kubectl annotate --overwrite Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation="false"
You can also do the same by removing the pause-reconciliation
annotation.
kubectl annotate Kafka <name_of_custom_resource> strimzi.io/pause-reconciliation-
On the next reconciliation, the Cluster Operator performs a rolling update of ZooKeeper, Kafka, and other components to trust the new CA certificate.
When the rolling update is complete, the Cluster Operator will start a new one to generate new server certificates signed by the new CA key.
If maintenance time windows are configured, the Cluster Operator will roll the pods at the first reconciliation within the next maintenance time window.
-
Wait until the rolling updates to move to the new CA certificate are complete.
-
Remove any outdated certificates from the secret configuration to ensure that the cluster no longer trusts them.
kubectl edit secret <ca_certificate_secret_name>
Example secret configuration with the old certificate removed
apiVersion: v1
kind: Secret
data:
ca.crt: GCa6LS3RTHeKFiFDGBOUDYFAZ0F...
metadata:
annotations:
strimzi.io/ca-cert-generation: "1"
labels:
strimzi.io/cluster: my-cluster
strimzi.io/kind: Kafka
name: my-cluster-cluster-ca-cert
#...
type: Opaque
-
Start a manual rolling update of your cluster to pick up the changes made to the secret configuration.
Security context defines constraints on pods and containers.
By specifying a security context, pods and containers only have the permissions they need.
For example, permissions can control runtime operations or access to resources.
Use security provider plugins or template configuration to apply security context to Strimzi pods and containers.
Apply security context at the pod or container level:
- Pod-level security context
-
Pod-level security context is applied to all containers in a specific pod.
- Container-level security context
-
Container-level security context is applied to a specific container.
With Strimzi, security context is applied through one or both of the following methods:
- Template configuration
-
Use template
configuration of Strimzi custom resources to specify security context at the pod or container level.
- Pod security provider plugins
-
Use pod security provider plugins to automatically set security context across all pods and containers using preconfigured settings.
Pod security providers offer a simpler alternative to specifying security context through template
configuration.
You can use both approaches.
The template
approach has a higher priority.
Security context configured through template
properties overrides the configuration set by pod security providers.
So you might use pod security providers to automatically configure the security context for most containers.
And also use template
configuration to set container-specific security context where needed.
The template
approach provides flexibility, but it also means you have to configure security context in numerous places to capture the security you want for all pods and containers.
For example, you’ll need to apply the configuration to each pod in a Kafka cluster, as well as the pods for deployments of other Kafka components.
To avoid repeating the same configuration, you can use the following pod security provider plugins so that the security configuration is in one place.
- Baseline Provider
-
The Baseline Provider is based on the Kubernetes baseline security profile. The baseline profile prevents privilege escalations and defines other standard access controls and limitations.
- Restricted Provider
-
The Restricted Provider is based on the Kubernetes restricted security profile. The restricted profile is more restrictive than the baseline profile, and is used where security needs to be tighter.
In the following example, security context is configured for Kafka brokers in the template
configuration of the Kafka
resource.
Security context is specified at the pod and container level.
Example template
configuration for security context
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
# ...
kafka:
template:
pod: # (1)
securityContext:
runAsUser: 1000001
fsGroup: 0
kafkaContainer: # (2)
securityContext:
runAsUser: 2000
# ...
-
Pod security context
-
Container security context of the Kafka broker container
The Baseline Provider is the default pod security provider.
It configures the pods managed by Strimzi with a baseline security profile.
The baseline profile is compatible with previous versions of Strimzi.
The Baseline Provider is enabled by default if you don’t specify a provider.
Though you can enable it explicitly by setting the STRIMZI_POD_SECURITY_PROVIDER_CLASS
environment variable to baseline
when configuring the Cluster Operator.
Configuration for the Baseline Provider
# ...
env:
# ...
- name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
value: baseline
# ...
Instead of specifying baseline
as the value, you can specify the io.strimzi.plugin.security.profiles.impl.BaselinePodSecurityProvider
fully-qualified domain name.
The Restricted Provider provides a higher level of security than the Baseline Provider.
It configures the pods managed by Strimzi with a restricted security profile.
You enable the Restricted Provider by setting the STRIMZI_POD_SECURITY_PROVIDER_CLASS
environment variable to restricted
when configuring the Cluster Operator.
Configuration for the Restricted Provider
# ...
env:
# ...
- name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
value: restricted
# ...
Instead of specifying restricted
as the value, you can specify the io.strimzi.plugin.security.profiles.impl.RestrictedPodSecurityProvider
fully-qualified domain name.
If you change to the Restricted Provider from the default Baseline Provider, the following restrictions are implemented in addition to the constraints defined in the baseline security profile:
-
Limits allowed volume types
-
Disallows privilege escalation
-
Requires applications to run under a non-root user
-
Requires seccomp
(secure computing mode) profiles to be set as RuntimeDefault
or Localhost
-
Limits container capabilities to use only the NET_BIND_SERVICE
capability
With the Restricted Provider enabled, containers created by the Cluster Operator are set with the following security context.
Cluster Operator with restricted security context configuration
# ...
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
# ...
Note
|
Container capabilities and seccomp are Linux kernel features that support container security.
-
Capabilities add fine-grained privileges for processes running on a container. The NET_BIND_SERVICE capability allows non-root user applications to bind to ports below 1024.
-
seccomp profiles limit the processes running in a container to only a subset of system calls.
The RuntimeDefault profile provides a default set of system calls.
A LocalHost profile uses a profile defined in a file on the node.
|
Security pod providers configure the security context constraints of the pods and containers created by the Cluster Operator.
The Baseline Provider is the default pod security provider used by Strimzi.
You can switch to the Restricted Provider by changing the STRIMZI_POD_SECURITY_PROVIDER_CLASS
environment variable in the Cluster Operator configuration.
To make the required changes, configure the 060-Deployment-strimzi-cluster-operator.yaml
Cluster Operator installation file located in install/cluster-operator/
.
By enabling a new pod security provider, any pods or containers created by the Cluster Operator are subject to the limitations it imposes.
Pods and containers that are already running are restarted for the changes to take affect.
Procedure
Edit the Deployment
resource that is used to deploy the Cluster Operator, which is defined in the 060-Deployment-strimzi-cluster-operator.yaml
file.
-
Add or amend the STRIMZI_POD_SECURITY_PROVIDER_CLASS
environment variable with a value of restricted
.
Cluster Operator configuration for the Restricted Provider
# ...
env:
# ...
- name: STRIMZI_POD_SECURITY_PROVIDER_CLASS
value: restricted
# ...
Or you can specify the io.strimzi.plugin.security.profiles.impl.RestrictedPodSecurityProvider
fully-qualified domain name.
-
Deploy the Cluster Operator:
kubectl create -f install/cluster-operator -n myproject
-
(Optional) Use template
configuration to set security context for specific components at the pod or container level.
Adding security context through template
configuration
template:
pod:
securityContext:
runAsUser: 1000001
fsGroup: 0
kafkaContainer:
securityContext:
runAsUser: 2000
# ...
If you apply specific security context for a component using template
configuration, it takes priority over the general configuration provided by the pod security provider.
If Strimzi’s Baseline Provider and Restricted Provider don’t quite match your needs, you can develop a custom pod security provider to deliver all-encompassing pod and container security context constraints.
Implement a custom pod security provider to apply your own security context profile.
You can decide what applications and privileges to include in the profile.
Your custom pod security provider can implement the PodSecurityProvider.java
interface that gets the security context for pods and containers; or it can extend the Baseline Provider or Restricted Provider classes.
The pod security provider plugins use the Java Service Provider Interface, so your custom pod security provider also requires a provider configuration file for service discovery.
To implement your own provider, the general steps include the following:
-
Build the JAR file for the provider.
-
Add the JAR file to the Cluster Operator image.
-
Specify the custom pod security provider when setting the Cluster Operator environment variable STRIMZI_POD_SECURITY_PROVIDER_CLASS
.
Handling of security context depends on the tooling of the Kubernetes platform you are using.
For example, OpenShift uses built-in security context constraints (SCCs) to control permissions.
SCCs are the settings and strategies that control the security features a pod has access to.
By default, OpenShift injects security context configuration automatically.
In most cases, this means you don’t need to configure security context for the pods and containers created by the Cluster Operator.
Although you can still create and manage your own SCCs.
Scaling Kafka clusters by adding brokers can increase the performance and reliability of the cluster.
Adding more brokers increases available resources, allowing the cluster to handle larger workloads and process more messages.
It can also improve fault tolerance by providing more replicas and backups.
Conversely, removing underutilized brokers can reduce resource consumption and improve efficiency.
Scaling must be done carefully to avoid disruption or data loss.
By redistributing partitions across all brokers in the cluster, the resource utilization of each broker is reduced, which can increase the overall throughput of the cluster.
Note
|
To increase the throughput of a Kafka topic, you can increase the number of partitions for that topic.
This allows the load of the topic to be shared between different brokers in the cluster.
However, if every broker is constrained by a specific resource (such as I/O), adding more partitions will not increase the throughput.
In this case, you need to add more brokers to the cluster.
|
Adjusting the Kafka.spec.kafka.replicas
configuration affects the number of brokers in the cluster that act as replicas.
The actual replication factor for topics is determined by settings for the default.replication.factor
and min.insync.replicas
, and the number of available brokers.
For example, a replication factor of 3 means that each partition of a topic is replicated across three brokers, ensuring fault tolerance in the event of a broker failure.
Example replica configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
# ...
config:
# ...
default.replication.factor: 3
min.insync.replicas: 2
# ...
When adding brokers through the Kafka
resource configuration, node IDs start at 0 (zero) and the Cluster Operator assigns the next lowest ID to a new node.
The broker removal process starts from the broker pod with the highest ID in the cluster.
If you are managing nodes in the cluster using node pools, adjust the KafkaNodePool.spec.replicas
configuration to change the number of nodes in the node pool.
Additionally, when scaling existing clusters with node pools, you can assign node IDs for the scaling operations.
When you add add or remove brokers, Kafka does not automatically reassign partitions.
The best way to do this is using Cruise Control.
You can use Cruise Control’s add-brokers
and remove-brokers
modes when scaling a cluster up or down.
-
Use the add-brokers
mode after scaling up a Kafka cluster to move partition replicas from existing brokers to the newly added brokers.
-
Use the remove-brokers
mode before scaling down a Kafka cluster to move partition replicas off the brokers that are going to be removed.
By default, Strimzi performs a check to ensure that there are no partition replicas on brokers before initiating a scale-down operation on a Kafka cluster.
The check applies to nodes in node pools that perform the role of broker only or a dual role of broker and controller.
If replicas are found, the scale-down is not done in order to prevent potential data loss.
To scale-down the cluster, no replicas must be left on the broker before trying to scale it down again.
However, there may be scenarios where you want to bypass this mechanism.
Disabling the check might be necessary on busy clusters, for example, because new topics keep generating replicas for the broker.
This situation can indefinitely block the scale-down, even when brokers are nearly empty.
Overriding the blocking mechanism in this way has an impact:
the presence of topics on the broker being scaled down will likely cause a reconciliation failure for the Kafka cluster.
You can bypass the blocking mechanism by annotating the Kafka
resource for the Kafka cluster.
Annotate the resource by setting the strimzi.io/skip-broker-scaledown-check
annotation to true
:
Adding the annotation to skip checks on scale-down operations
kubectl annotate Kafka my-kafka-cluster strimzi.io/skip-broker-scaledown-check="true"
This annotation instructs Strimzi to skip the scale-down check.
Replace my-kafka-cluster
with the name of your specific Kafka
resource.
To restore the check for scale-down operations, remove the annotation:
Removing the annotation to skip checks on scale-down operations
kubectl annotate Kafka my-kafka-cluster strimzi.io/skip-broker-scaledown-check-
Cruise Control is an open source system that supports the following Kafka operations:
The operations help with running a more balanced Kafka cluster that uses broker pods more efficiently.
A typical cluster can become unevenly loaded over time.
Partitions that handle large amounts of message traffic might not be evenly distributed across the available brokers.
To rebalance the cluster, administrators must monitor the load on brokers and manually reassign busy partitions to brokers with spare capacity.
Cruise Control automates the cluster rebalancing process.
It constructs a workload model of resource utilization for the cluster—based on CPU, disk, and network load—and generates optimization proposals (that you can approve or reject) for more balanced partition assignments.
A set of configurable optimization goals is used to calculate these proposals.
You can generate optimization proposals in specific modes.
The default full
mode rebalances partitions across all brokers.
You can also use the add-brokers
and remove-brokers
modes to accommodate changes when scaling a cluster up or down.
When you approve an optimization proposal, Cruise Control applies it to your Kafka cluster.
You configure and generate optimization proposals using a KafkaRebalance
resource.
You can configure the resource using an annotation so that optimization proposals are approved automatically or manually.
Cruise Control consists of four main components—the Load Monitor, the Analyzer, the Anomaly Detector, and the Executor—and a REST API for client interactions.
Strimzi utilizes the REST API to support the following Cruise Control features:
- Optimization goals
-
An optimization goal describes a specific objective to achieve from a rebalance.
For example, a goal might be to distribute topic replicas across brokers more evenly.
You can change what goals to include through configuration.
A goal is defined as a hard goal or soft goal.
You can add hard goals through Cruise Control deployment configuration.
You also have main, default, and user-provided goals that fit into each of these categories.
-
Hard goals are preset and must be satisfied for an optimization proposal to be successful.
-
Soft goals do not need to be satisfied for an optimization proposal to be successful.
They can be set aside if it means that all hard goals are met.
-
Main goals are inherited from Cruise Control. Some are preset as hard goals.
Main goals are used in optimization proposals by default.
-
Default goals are the same as the main goals by default.
You can specify your own set of default goals.
-
User-provided goals are a subset of default goals that are configured for generating a specific optimization proposal.
- Optimization proposals
-
Optimization proposals comprise the goals you want to achieve from a rebalance.
You generate an optimization proposal to create a summary of proposed changes and the results that are possible with the rebalance.
The goals are assessed in a specific order of priority.
You can then choose to approve or reject the proposal.
You can reject the proposal to run it again with an adjusted set of goals.
You can generate an optimization proposal in one of three modes.
-
full
is the default mode and runs a full rebalance.
-
add-brokers
is the mode you use after adding brokers when scaling up a Kafka cluster.
-
remove-brokers
is the mode you use before removing brokers when scaling down a Kafka cluster.
Other Cruise Control features are not currently supported, including self healing, notifications, and write-your-own goals.
Optimization goals are constraints on workload redistribution and resource utilization across a Kafka cluster.
To rebalance a Kafka cluster, Cruise Control uses optimization goals to generate optimization proposals, which you can approve or reject.
Strimzi supports most of the optimization goals developed in the Cruise Control project.
The supported goals, in the default descending order of priority, are as follows:
-
Rack-awareness
-
Minimum number of leader replicas per broker for a set of topics
-
Replica capacity
-
Capacity goals
-
Replica distribution
-
Potential network output
-
Resource distribution goals
-
Disk utilization distribution
-
Network inbound utilization distribution
-
Network outbound utilization distribution
-
CPU utilization distribution
-
Leader bytes-in rate distribution
-
Topic replica distribution
-
Leader replica distribution
-
Preferred leader election
-
Intra-broker disk capacity
-
Intra-broker disk usage distribution
For more information on each optimization goal, see Goals in the Cruise Control Wiki.
Note
|
"Write your own" goals and Kafka assigner goals are not yet supported.
|
You configure optimization goals in Kafka
and KafkaRebalance
custom resources.
Cruise Control has configurations for hard optimization goals that must be satisfied, as well as main, default, and user-provided optimization goals.
You can specify optimization goals in the following configuration:
-
Main goals — Kafka.spec.cruiseControl.config.goals
-
Hard goals — Kafka.spec.cruiseControl.config.hard.goals
-
Default goals — Kafka.spec.cruiseControl.config.default.goals
-
User-provided goals — KafkaRebalance.spec.goals
Note
|
Resource distribution goals are subject to capacity limits on broker resources.
|
Hard goals are goals that must be satisfied in optimization proposals.
Goals that are not defined as hard goals in the Cruise Control code are known as soft goals.
You can think of soft goals as best effort goals: they do not need to be satisfied in optimization proposals, but are included in optimization calculations.
An optimization proposal that violates one or more soft goals, but satisfies all hard goals, is valid.
Cruise Control will calculate optimization proposals that satisfy all the hard goals and as many soft goals as possible (in their priority order).
An optimization proposal that does not satisfy all the hard goals is rejected by Cruise Control and not sent to the user for approval.
Note
|
For example, you might have a soft goal to distribute a topic’s replicas evenly across the cluster (the topic replica distribution goal).
Cruise Control will ignore this goal if doing so enables all the configured hard goals to be met.
|
RackAwareGoal; ReplicaCapacityGoal; DiskCapacityGoal; NetworkInboundCapacityGoal; NetworkOutboundCapacityGoal; CpuCapacityGoal
In your Cruise Control deployment configuration, you can specify which hard goals to enforce using the hard.goals
property in Kafka.spec.cruiseControl.config
.
-
To enforce execution of all hard goals, simply omit the hard.goals
property.
-
To change which hard goals Cruise Control enforces, specify the required goals in the hard.goals
property using their fully-qualified domain names.
-
To prevent execution of a specific hard goal, ensure that the goal is not included in both the default.goals
and hard.goals
list configurations.
Note
|
It is not possible to configure which goals are considered soft or hard goals.
This distinction is determined by the Cruise Control code.
|
Example Kafka
configuration for hard optimization goals
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
zookeeper:
# ...
entityOperator:
topicOperator: {}
userOperator: {}
cruiseControl:
brokerCapacity:
inboundNetwork: 10000KB/s
outboundNetwork: 10000KB/s
config:
# Note that `default.goals` (superset) must also include all `hard.goals` (subset)
default.goals: >
com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkInboundCapacityGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkOutboundCapacityGoal
hard.goals: >
com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkInboundCapacityGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.NetworkOutboundCapacityGoal
# ...
Increasing the number of configured hard goals will reduce the likelihood of Cruise Control generating valid optimization proposals.
If skipHardGoalCheck: true
is specified in the KafkaRebalance
custom resource, Cruise Control does not check that the list of user-provided optimization goals (in KafkaRebalance.spec.goals
) contains all the configured hard goals (hard.goals
).
Therefore, if some, but not all, of the user-provided optimization goals are in the hard.goals
list, Cruise Control will still treat them as hard goals even if skipHardGoalCheck: true
is specified.
The main optimization goals are available to all users.
Goals that are not listed in the main optimization goals are not available for use in Cruise Control operations.
Unless you change the Cruise Control deployment configuration, Strimzi will inherit the following main optimization goals from Cruise Control, in descending priority order:
RackAwareGoal; MinTopicLeadersPerBrokerGoal; ReplicaCapacityGoal; DiskCapacityGoal; NetworkInboundCapacityGoal; NetworkOutboundCapacityGoal; CpuCapacityGoal; ReplicaDistributionGoal; PotentialNwOutGoal; DiskUsageDistributionGoal; NetworkInboundUsageDistributionGoal; NetworkOutboundUsageDistributionGoal; CpuUsageDistributionGoal; TopicReplicaDistributionGoal; LeaderReplicaDistributionGoal; LeaderBytesInDistributionGoal; PreferredLeaderElectionGoal
To reduce complexity, we recommend that you use the inherited main optimization goals, unless you need to completely exclude one or more goals from use in KafkaRebalance
resources. The priority order of the main optimization goals can be modified, if desired, in the configuration for default optimization goals.
You configure main optimization goals, if necessary, in the Cruise Control deployment configuration: Kafka.spec.cruiseControl.config.goals
-
To accept the inherited main optimization goals, do not specify the goals
property in Kafka.spec.cruiseControl.config
.
-
If you need to modify the inherited main optimization goals, specify a list of goals, in descending priority order, in the goals
configuration option.
Note
|
To avoid errors when generating optimization proposals, make sure that any changes you make to the goals or default.goals in Kafka.spec.cruiseControl.config include all of the hard goals specified for the hard.goals property. To clarify, the hard goals must also be specified (as a subset) for the main optimization goals and default goals.
|
Cruise Control uses the default optimization goals to generate the cached optimization proposal.
For more information about the cached optimization proposal, see Optimization proposals overview.
Unless you specify default.goals
in the Cruise Control deployment configuration, the main optimization goals are used as the default optimization goals.
In this case, the cached optimization proposal is generated using the main optimization goals.
-
To use the main optimization goals as the default goals, do not specify the default.goals
property in Kafka.spec.cruiseControl.config
.
-
To modify the default optimization goals, edit the default.goals
property in Kafka.spec.cruiseControl.config
.
You must use a subset of the main optimization goals.
Example Kafka
configuration for default optimization goals
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
zookeeper:
# ...
entityOperator:
topicOperator: {}
userOperator: {}
cruiseControl:
brokerCapacity:
inboundNetwork: 10000KB/s
outboundNetwork: 10000KB/s
config:
# Note that `default.goals` (superset) must also include all `hard.goals` (subset)
default.goals: >
com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.ReplicaCapacityGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.DiskCapacityGoal
hard.goals: >
com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal
# ...
If no default optimization goals are specified, the cached proposal is generated using the main optimization goals.
User-provided optimization goals narrow down the configured default goals for a particular optimization proposal.
You can set them, as required, in spec.goals
in a KafkaRebalance
custom resource:
KafkaRebalance.spec.goals
User-provided optimization goals can generate optimization proposals for different scenarios.
For example, you might want to optimize leader replica distribution across the Kafka cluster without considering disk capacity or disk utilization.
So, you create a KafkaRebalance
custom resource containing a single user-provided goal for leader replica distribution.
User-provided optimization goals must:
To ignore the configured hard goals when generating an optimization proposal, add the skipHardGoalCheck: true
property to the KafkaRebalance
custom resource. See Generating optimization proposals.
Configure a KafkaRebalance
resource to generate optimization proposals and apply the suggested changes.
An optimization proposal is a summary of proposed changes that would produce a more balanced Kafka cluster, with partition workloads distributed more evenly among the brokers.
All optimization proposals are estimates of the impact of a proposed rebalance.
You can approve or reject a proposal.
You cannot approve a cluster rebalance without first generating the optimization proposal.
You can run optimization proposals in one of the following rebalancing modes:
-
full
-
add-brokers
-
remove-brokers
You specify a rebalancing mode using the spec.mode
property of the KafkaRebalance
custom resource.
full
-
The full
mode runs a full rebalance by moving replicas across all the brokers in the cluster.
This is the default mode if the spec.mode
property is not defined in the KafkaRebalance
custom resource.
add-brokers
-
The add-brokers
mode is used after scaling up a Kafka cluster by adding one or more brokers.
Normally, after scaling up a Kafka cluster, new brokers are used to host only the partitions of newly created topics.
If no new topics are created, the newly added brokers are not used and the existing brokers remain under the same load.
By using the add-brokers
mode immediately after adding brokers to the cluster, the rebalancing operation moves replicas from existing brokers to the newly added brokers.
You specify the new brokers as a list using the spec.brokers
property of the KafkaRebalance
custom resource.
remove-brokers
-
The remove-brokers
mode is used before scaling down a Kafka cluster by removing one or more brokers.
If you scale down a Kafka cluster, brokers are shut down even if they host replicas.
This can lead to under-replicated partitions and possibly result in some partitions being under their minimum ISR (in-sync replicas).
To avoid this potential problem, the remove-brokers
mode moves replicas off the brokers that are going to be removed.
When these brokers are not hosting replicas anymore, you can safely run the scaling down operation.
You specify the brokers you’re removing as a list in the spec.brokers
property in the KafkaRebalance
custom resource.
In general, use the full
rebalance mode to rebalance a Kafka cluster by spreading the load across brokers.
Use the add-brokers
and remove-brokers
modes only if you want to scale your cluster up or down and rebalance the replicas accordingly.
The procedure to run a rebalance is actually the same across the three different modes.
The only difference is with specifying a mode through the spec.mode
property and, if needed, listing brokers that have been added or will be removed through the spec.brokers
property.
When an optimization proposal is generated, a summary and broker load is returned.
- Summary
-
The summary is contained in the KafkaRebalance
resource. The summary provides an overview of the proposed cluster rebalance and indicates the scale of the changes involved.
A summary of a successfully generated optimization proposal is contained in the Status.OptimizationResult
property of the KafkaRebalance
resource.
The information provided is a summary of the full optimization proposal.
- Broker load
-
The broker load is stored in a ConfigMap that contains data as a JSON string. The broker load shows before and after values for the proposed rebalance, so you can see the impact on each of the brokers in the cluster.
An optimization proposal summary shows the proposed scope of changes.
You can use the name of the KafkaRebalance
resource to return a summary from the command line.
Returning an optimization proposal summary
kubectl describe kafkarebalance <kafka_rebalance_resource_name> -n <namespace>
Returning an optimization proposal summary using jq
kubectl get kafkarebalance -o json | jq <jq_query>
.
Use the summary to decide whether to approve or reject an optimization proposal.
- Approving an optimization proposal
-
You approve the optimization proposal by setting the strimzi.io/rebalance
annotation of the KafkaRebalance
resource to approve
.
Cruise Control applies the proposal to the Kafka cluster and starts a cluster rebalance operation.
- Rejecting an optimization proposal
-
If you choose not to approve an optimization proposal,
you can change the optimization goals or update any of the rebalance performance tuning options, and then generate another proposal.
You can generate a new optimization proposal for a KafkaRebalance
resource by setting the strimzi.io/rebalance
annotation to refresh
.
Use optimization proposals to assess the movements required for a rebalance.
For example, a summary describes inter-broker and intra-broker movements.
Inter-broker rebalancing moves data between separate brokers.
Intra-broker rebalancing moves data between disks on the same broker when you are using a JBOD storage configuration.
Such information can be useful even if you don’t go ahead and approve the proposal.
You might reject an optimization proposal, or delay its approval, because of the additional load on a Kafka cluster when rebalancing.
In the following example, the proposal suggests the rebalancing of data between separate brokers.
The rebalance involves the movement of 55 partition replicas, totaling 12MB of data, across the brokers.
Though the inter-broker movement of partition replicas has a high impact on performance, the total amount of data is not large.
If the total data was much larger, you could reject the proposal, or time when to approve the rebalance to limit the impact on the performance of the Kafka cluster.
Rebalance performance tuning options can help reduce the impact of data movement.
If you can extend the rebalance period, you can divide the rebalance into smaller batches.
Fewer data movements at a single time reduces the load on the cluster.
Example optimization proposal summary
Name: my-rebalance
Namespace: myproject
Labels: strimzi.io/cluster=my-cluster
Annotations: API Version: kafka.strimzi.io/v1alpha1
Kind: KafkaRebalance
Metadata:
# ...
Status:
Conditions:
Last Transition Time: 2022-04-05T14:36:11.900Z
Status: ProposalReady
Type: State
Observed Generation: 1
Optimization Result:
Data To Move MB: 0
Excluded Brokers For Leadership:
Excluded Brokers For Replica Move:
Excluded Topics:
Intra Broker Data To Move MB: 12
Monitored Partitions Percentage: 100
Num Intra Broker Replica Movements: 0
Num Leader Movements: 24
Num Replica Movements: 55
On Demand Balancedness Score After: 82.91290759174306
On Demand Balancedness Score Before: 78.01176356230222
Recent Windows: 5
Session Id: a4f833bd-2055-4213-bfdd-ad21f95bf184
The proposal will also move 24 partition leaders to different brokers.
This requires a change to the ZooKeeper configuration, which has a low impact on performance.
The balancedness scores are measurements of the overall balance of the Kafka cluster before and after the optimization proposal is approved.
A balancedness score is based on optimization goals.
If all goals are satisfied, the score is 100.
The score is reduced for each goal that will not be met.
Compare the balancedness scores to see whether the Kafka cluster is less balanced than it could be following a rebalance.
To save time, you can automate the process of approving optimization proposals.
With automation, when you generate an optimization proposal it goes straight into a cluster rebalance.
To enable the optimization proposal auto-approval mechanism, create the KafkaRebalance
resource with the strimzi.io/rebalance-auto-approval
annotation set to true
.
If the annotation is not set or set to false
, the optimization proposal requires manual approval.
Example rebalance request with auto-approval mechanism enabled
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
annotations:
strimzi.io/rebalance-auto-approval: "true"
spec:
mode: # any mode
# ...
You can still check the status when automatically approving an optimization proposal.
The status of the KafkaRebalance
resource moves to Ready
when the rebalance is complete.
The following table explains the properties contained in the optimization proposal’s summary section.
Table 33. Properties contained in an optimization proposal summary
JSON property |
Description |
numIntraBrokerReplicaMovements
|
The total number of partition replicas that will be transferred between the disks of the cluster’s brokers.
Performance impact during rebalance operation: Relatively high, but lower than numReplicaMovements . |
excludedBrokersForLeadership
|
Not yet supported. An empty list is returned. |
numReplicaMovements
|
The number of partition replicas that will be moved between separate brokers.
Performance impact during rebalance operation: Relatively high. |
onDemandBalancednessScoreBefore, onDemandBalancednessScoreAfter
|
A measurement of the overall balancedness of a Kafka Cluster, before and after the optimization proposal was generated.
The score is calculated by subtracting the sum of the BalancednessScore of each violated soft goal from 100. Cruise Control assigns a BalancednessScore to every optimization goal based on several factors, including priority—the goal’s position in the list of default.goals or user-provided goals.
The Before score is based on the current configuration of the Kafka cluster.
The After score is based on the generated optimization proposal. |
intraBrokerDataToMoveMB
|
The sum of the size of each partition replica that will be moved between disks on the same broker (see also numIntraBrokerReplicaMovements ).
Performance impact during rebalance operation: Variable. The larger the number, the longer the cluster rebalance will take to complete. Moving a large amount of data between disks on the same broker has less impact than between separate brokers (see dataToMoveMB ). |
recentWindows
|
The number of metrics windows upon which the optimization proposal is based. |
dataToMoveMB
|
The sum of the size of each partition replica that will be moved to a separate broker (see also numReplicaMovements ).
Performance impact during rebalance operation: Variable. The larger the number, the longer the cluster rebalance will take to complete. |
monitoredPartitionsPercentage
|
The percentage of partitions in the Kafka cluster covered by the optimization proposal. Affected by the number of excludedTopics . |
excludedTopics
|
If you specified a regular expression in the spec.excludedTopicsRegex property in the KafkaRebalance resource, all topic names matching that expression are listed here.
These topics are excluded from the calculation of partition replica/leader movements in the optimization proposal. |
numLeaderMovements
|
The number of partitions whose leaders will be switched to different replicas. This involves a change to ZooKeeper configuration.
Performance impact during rebalance operation: Relatively low. |
excludedBrokersForReplicaMove
|
Not yet supported. An empty list is returned. |
The broker load is stored in a ConfigMap (with the same name as the KafkaRebalance custom resource) as a JSON formatted string. This JSON string consists of a JSON object with keys for each broker IDs linking to a number of metrics for each broker.
Each metric consist of three values.
The first is the metric value before the optimization proposal is applied, the second is the expected value of the metric after the proposal is applied, and the third is the difference between the first two values (after minus before).
Note
|
The ConfigMap appears when the KafkaRebalance resource is in the ProposalReady state and remains after the rebalance is complete.
|
You can use the name of the ConfigMap to view its data from the command line.
Returning ConfigMap data
kubectl describe configmaps <my_rebalance_configmap_name> -n <namespace>
Extracting the JSON string from the ConfigMap using jq
kubectl get configmaps <my_rebalance_configmap_name> -o json | jq '.["data"]["brokerLoad.json"]|fromjson|.'
The following table explains the properties contained in the optimization proposal’s broker load ConfigMap:
JSON property |
Description |
leaders
|
The number of replicas on this broker that are partition leaders. |
replicas
|
The number of replicas on this broker. |
cpuPercentage
|
The CPU utilization as a percentage of the defined capacity. |
diskUsedPercentage
|
The disk utilization as a percentage of the defined capacity. |
diskUsedMB
|
The absolute disk usage in MB. |
networkOutRate
|
The total network output rate for the broker. |
leaderNetworkInRate
|
The network input rate for all partition leader replicas on this broker. |
followerNetworkInRate
|
The network input rate for all follower replicas on this broker. |
potentialMaxNetworkOutRate
|
The hypothetical maximum network output rate that would be realized if this broker became the leader of all the replicas it currently hosts. |
Cruise Control maintains a cached optimization proposal based on the configured default optimization goals.
Generated from the workload model, the cached optimization proposal is updated every 15 minutes to reflect the current state of the Kafka cluster.
If you generate an optimization proposal using the default optimization goals, Cruise Control returns the most recent cached proposal.
To change the cached optimization proposal refresh interval, edit the proposal.expiration.ms
setting in the Cruise Control deployment configuration.
Consider a shorter interval for fast changing clusters, although this increases the load on the Cruise Control server.
You can adjust several performance tuning options for cluster rebalances.
These options control how partition replicas and leadership movements in a rebalance are executed, as well as the bandwidth that is allocated to a rebalance operation.
Optimization proposals are comprised of separate partition reassignment commands.
When you approve a proposal, the Cruise Control server applies these commands to the Kafka cluster.
A partition reassignment command consists of either of the following types of operations:
-
Partition movement: Involves transferring the partition replica and its data to a new location. Partition movements can take one of two forms:
-
Leadership movement: This involves switching the leader of the partition’s replicas.
Cruise Control issues partition reassignment commands to the Kafka cluster in batches.
The performance of the cluster during the rebalance is affected by the number of each type of movement contained in each batch.
Cluster rebalance performance is also influenced by the replica movement strategy that is applied to the batches of partition reassignment commands.
By default, Cruise Control uses the BaseReplicaMovementStrategy
, which simply applies the commands in the order they were generated.
However, if there are some very large partition reassignments early in the proposal, this strategy can slow down the application of the other reassignments.
Cruise Control provides four alternative replica movement strategies that can be applied to optimization proposals:
-
PrioritizeSmallReplicaMovementStrategy
: Order reassignments in order of ascending size.
-
PrioritizeLargeReplicaMovementStrategy
: Order reassignments in order of descending size.
-
PostponeUrpReplicaMovementStrategy
: Prioritize reassignments for replicas of partitions which have no out-of-sync replicas.
-
PrioritizeMinIsrWithOfflineReplicasStrategy
: Prioritize reassignments with (At/Under)MinISR partitions with offline replicas. This strategy will only work if cruiseControl.config.concurrency.adjuster.min.isr.check.enabled
is set to true
in the Kafka
custom resource’s spec.
These strategies can be configured as a sequence.
The first strategy attempts to compare two partition reassignments using its internal logic.
If the reassignments are equivalent, then it passes them to the next strategy in the sequence to decide the order, and so on.
Moving a large amount of data between disks on the same broker has less impact than between separate brokers.
If you are running a Kafka deployment that uses JBOD storage with multiple disks on the same broker, Cruise Control can balance partitions between the disks.
Note
|
If you are using JBOD storage with a single disk, intra-broker disk balancing will result in a proposal with 0 partition movements since there are no disks to balance between.
|
To perform an intra-broker disk balance, set rebalanceDisk
to true
under the KafkaRebalance.spec
.
When setting rebalanceDisk
to true
, do not set a goals
field in the KafkaRebalance.spec
, as Cruise Control will automatically set the intra-broker goals and ignore the inter-broker goals.
Cruise Control does not perform inter-broker and intra-broker balancing at the same time.
-
The Cruise Control server setting can be set in the Kafka custom resource under Kafka.spec.cruiseControl.config
.
-
The individual rebalance performance configurations can be set under KafkaRebalance.spec
.
The relevant configurations are summarized in the following table.
Table 34. Rebalance performance tuning configuration
Cruise Control properties |
KafkaRebalance properties |
Default |
Description |
num.concurrent.partition.movements.per.broker
|
concurrentPartitionMovementsPerBroker
|
5 |
The maximum number of inter-broker partition movements in each partition reassignment batch |
num.concurrent.intra.broker.partition.movements
|
concurrentIntraBrokerPartitionMovements
|
2 |
The maximum number of intra-broker partition movements in each partition reassignment batch |
num.concurrent.leader.movements
|
concurrentLeaderMovements
|
1000 |
The maximum number of partition leadership changes in each partition reassignment batch |
default.replication.throttle
|
replicationThrottle
|
Null (no limit) |
The bandwidth (in bytes per second) to assign to partition reassignment |
default.replica.movement.strategies
|
replicaMovementStrategies
|
BaseReplicaMovementStrategy
|
The list of strategies (in priority order) used to determine the order in which partition reassignment commands are executed for generated proposals.
For the server setting, use a comma separated string with the fully qualified names of the strategy class (add com.linkedin.kafka.cruisecontrol.executor.strategy. to the start of each class name).
For the KafkaRebalance resource setting use a YAML array of strategy class names. |
- |
rebalanceDisk
|
false |
Enables intra-broker disk balancing, which balances disk space utilization between disks on the same broker. Only applies to Kafka deployments that use JBOD storage with multiple disks. |
Changing the default settings affects the length of time that the rebalance takes to complete, as well as the load placed on the Kafka cluster during the rebalance.
Using lower values reduces the load but increases the amount of time taken, and vice versa.
Configure a Kafka
resource to deploy Cruise Control alongside a Kafka cluster.
You can use the cruiseControl
properties of the Kafka
resource to configure the deployment.
Deploy one instance of Cruise Control per Kafka cluster.
Use goals
configuration in the Cruise Control config
to specify optimization goals for generating optimization proposals.
You can use brokerCapacity
to change the default capacity limits for goals related to resource distribution.
If brokers are running on nodes with heterogeneous network resources, you can use overrides
to set network capacity limits for each broker.
If an empty object ({}
) is used for the cruiseControl
configuration, all properties use their default values.
Procedure
-
Edit the cruiseControl
property for the Kafka
resource.
The properties you can configure are shown in this example configuration:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
# ...
cruiseControl:
brokerCapacity: # (1)
inboundNetwork: 10000KB/s
outboundNetwork: 10000KB/s
overrides: # (2)
- brokers: [0]
inboundNetwork: 20000KiB/s
outboundNetwork: 20000KiB/s
- brokers: [1, 2]
inboundNetwork: 30000KiB/s
outboundNetwork: 30000KiB/s
# ...
config: # (3)
# Note that `default.goals` (superset) must also include all `hard.goals` (subset)
default.goals: > # (4)
com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.ReplicaCapacityGoal,
com.linkedin.kafka.cruisecontrol.analyzer.goals.DiskCapacityGoal
# ...
hard.goals: >
com.linkedin.kafka.cruisecontrol.analyzer.goals.RackAwareGoal
# ...
cpu.balance.threshold: 1.1
metadata.max.age.ms: 300000
send.buffer.bytes: 131072
webserver.http.cors.enabled: true # (5)
webserver.http.cors.origin: "*"
webserver.http.cors.exposeheaders: "User-Task-ID,Content-Type"
# ...
resources: # (6)
requests:
cpu: 1
memory: 512Mi
limits:
cpu: 2
memory: 2Gi
logging: # (7)
type: inline
loggers:
rootLogger.level: INFO
template: # (8)
pod:
metadata:
labels:
label1: value1
securityContext:
runAsUser: 1000001
fsGroup: 0
terminationGracePeriodSeconds: 120
readinessProbe: # (9)
initialDelaySeconds: 15
timeoutSeconds: 5
livenessProbe:
initialDelaySeconds: 15
timeoutSeconds: 5
metricsConfig: # (10)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: cruise-control-metrics
key: metrics-config.yml
# ...
-
Capacity limits for broker resources.
-
Overrides set network capacity limits for specific brokers when running on nodes with heterogeneous network resources.
-
Cruise Control configuration. Standard Cruise Control configuration may be provided, restricted to those properties not managed directly by Strimzi.
-
Optimization goals configuration, which can include configuration for default optimization goals (default.goals
), main optimization goals (goals
), and hard goals (hard.goals
).
-
CORS enabled and configured for read-only access to the Cruise Control API.
-
Requests for reservation of supported resources, currently cpu
and memory
, and limits to specify the maximum resources that can be consumed.
-
Cruise Control loggers and log levels added directly (inline
) or indirectly (external
) through a ConfigMap. A custom Log4j configuration must be placed under the log4j.properties
key in the ConfigMap. Cruise Control has a single logger named rootLogger.level
. You can set the log level to INFO, ERROR, WARN, TRACE, DEBUG, FATAL or OFF.
-
Template customization. Here a pod is scheduled with additional security attributes.
-
Healthchecks to know when to restart a container (liveness) and when a container can accept traffic (readiness).
-
Prometheus metrics enabled. In this example, metrics are configured for the Prometheus JMX Exporter (the default metrics exporter).
-
Create or update the resource:
kubectl apply -f <kafka_configuration_file>
-
Check the status of the deployment:
kubectl get deployments -n <my_cluster_operator_namespace>
Output shows the deployment name and readiness
NAME READY UP-TO-DATE AVAILABLE
my-cluster-cruise-control 1/1 1 1
my-cluster
is the name of the Kafka cluster.
READY
shows the number of replicas that are ready/expected.
The deployment is successful when the AVAILABLE
output shows 1
.
Auto-created topics
The following table shows the three topics that are automatically created when Cruise Control is deployed. These topics are required for Cruise Control to work properly and must not be deleted or changed. You can change the name of the topic using the specified configuration option.
Table 35. Auto-created topics
Auto-created topic configuration |
Default topic name |
Created by |
Function |
metric.reporter.topic
|
strimzi.cruisecontrol.metrics
|
Strimzi Metrics Reporter |
Stores the raw metrics from the Metrics Reporter in each Kafka broker. |
partition.metric.sample.store.topic
|
strimzi.cruisecontrol.partitionmetricsamples
|
Cruise Control |
Stores the derived metrics for each partition. These are created by the Metric Sample Aggregator. |
broker.metric.sample.store.topic
|
strimzi.cruisecontrol.modeltrainingsamples
|
Cruise Control |
Stores the metrics samples used to create the Cluster Workload Model. |
To prevent the removal of records that are needed by Cruise Control, log compaction is disabled in the auto-created topics.
Note
|
If the names of the auto-created topics are changed in a Kafka cluster that already has Cruise Control enabled, the old topics will not be deleted and should be manually removed.
|
When you create or update a KafkaRebalance
resource, Cruise Control generates an optimization proposal for the Kafka cluster based on the configured optimization goals.
Analyze the information in the optimization proposal and decide whether to approve it.
You can use the results of the optimization proposal to rebalance your Kafka cluster.
You can run the optimization proposal in one of the following modes:
-
full
(default)
-
add-brokers
-
remove-brokers
The mode you use depends on whether you are rebalancing across all the brokers already running in the Kafka cluster;
or you want to rebalance after scaling up or before scaling down your Kafka cluster.
For more information, see Rebalancing modes with broker scaling.
Prerequisites
-
You have deployed Cruise Control to your Strimzi cluster.
-
You have configured optimization goals and, optionally, capacity limits on broker resources.
Procedure
-
Create a KafkaRebalance
resource and specify the appropriate mode.
full
mode (default)
-
To use the default optimization goals defined in the Kafka
resource, leave the spec
property empty.
Cruise Control rebalances a Kafka cluster in full
mode by default.
Example configuration with full rebalancing by default
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec: {}
You can also run a full rebalance by specifying the full
mode through the spec.mode
property.
Example configuration specifying full
mode
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec:
mode: full
add-brokers
mode
-
If you want to rebalance a Kafka cluster after scaling up, specify the add-brokers
mode.
In this mode, existing replicas are moved to the newly added brokers.
You need to specify the brokers as a list.
Example configuration specifying add-brokers
mode
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec:
mode: add-brokers
brokers: [3, 4] (1)
-
List of newly added brokers added by the scale up operation. This property is mandatory.
remove-brokers
mode
-
If you want to rebalance a Kafka cluster before scaling down, specify the remove-brokers
mode.
In this mode, replicas are moved off the brokers that are going to be removed.
You need to specify the brokers that are being removed as a list.
Example configuration specifying remove-brokers
mode
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec:
mode: remove-brokers
brokers: [3, 4] (1)
-
List of brokers to be removed by the scale down operation. This property is mandatory.
Note
|
The following steps and the steps to approve or stop a rebalance are the same regardless of the rebalance mode you are using.
|
-
To configure user-provided optimization goals instead of using the default goals, add the goals
property and enter one or more goals.
In the following example, rack awareness and replica capacity are configured as user-provided optimization goals:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec:
goals:
- RackAwareGoal
- ReplicaCapacityGoal
-
To ignore the configured hard goals, add the skipHardGoalCheck: true
property:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
spec:
goals:
- RackAwareGoal
- ReplicaCapacityGoal
skipHardGoalCheck: true
-
(Optional) To approve the optimization proposal automatically, set the strimzi.io/rebalance-auto-approval
annotation to true
:
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaRebalance
metadata:
name: my-rebalance
labels:
strimzi.io/cluster: my-cluster
annotations:
strimzi.io/rebalance-auto-approval: "true"
spec:
goals:
- RackAwareGoal
- ReplicaCapacityGoal
skipHardGoalCheck: true
-
Create or update the resource:
kubectl apply -f <kafka_rebalance_configuration_file>
The Cluster Operator requests the optimization proposal from Cruise Control.
This might take a few minutes depending on the size of the Kafka cluster.
-
If you used the automatic approval mechanism, wait for the status of the optimization proposal to change to Ready
.
If you haven’t enabled the automatic approval mechanism, wait for the status of the optimization proposal to change to ProposalReady
:
kubectl get kafkarebalance -o wide -w -n <namespace>
PendingProposal
-
A PendingProposal
status means the rebalance operator is polling the Cruise Control API to check if the optimization proposal is ready.
ProposalReady
-
A ProposalReady
status means the optimization proposal is ready for review and approval.
When the status changes to ProposalReady
, the optimization proposal is ready to approve.
-
Review the optimization proposal.
The optimization proposal is contained in the Status.Optimization Result
property of the KafkaRebalance
resource.
kubectl describe kafkarebalance <kafka_rebalance_resource_name>
Example optimization proposal
Status:
Conditions:
Last Transition Time: 2020-05-19T13:50:12.533Z
Status: ProposalReady
Type: State
Observed Generation: 1
Optimization Result:
Data To Move MB: 0
Excluded Brokers For Leadership:
Excluded Brokers For Replica Move:
Excluded Topics:
Intra Broker Data To Move MB: 0
Monitored Partitions Percentage: 100
Num Intra Broker Replica Movements: 0
Num Leader Movements: 0
Num Replica Movements: 26
On Demand Balancedness Score After: 81.8666802863978
On Demand Balancedness Score Before: 78.01176356230222
Recent Windows: 1
Session Id: 05539377-ca7b-45ef-b359-e13564f1458c
The properties in the Optimization Result
section describe the pending cluster rebalance operation.
For descriptions of each property, see Contents of optimization proposals.
Insufficient CPU capacity
If a Kafka cluster is overloaded in terms of CPU utilization, you might see an insufficient CPU capacity error in the KafkaRebalance
status.
It’s worth noting that this utilization value is unaffected by the excludedTopics
configuration.
Although optimization proposals will not reassign replicas of excluded topics, their load is still considered in the utilization calculation.
Example CPU utilization error
com.linkedin.kafka.cruisecontrol.exception.OptimizationFailureException:
[CpuCapacityGoal] Insufficient capacity for cpu (Utilization 615.21, Allowed Capacity 420.00, Threshold: 0.70). Add at least 3 brokers with the same cpu capacity (100.00) as broker-0. Add at least 3 brokers with the same cpu capacity (100.00) as broker-0.
Note
|
The error shows CPU capacity as a percentage rather than the number of CPU cores.
For this reason, it does not directly map to the number of CPUs configured in the Kafka custom resource.
It is like having a single virtual CPU per broker, which has the cycles of the CPUs configured in Kafka.spec.kafka.resources.limits.cpu .
This has no effect on the rebalance behavior, since the ratio between CPU utilization and capacity remains the same.
|
You can approve an optimization proposal generated by Cruise Control, if its status is ProposalReady
.
Cruise Control will then apply the optimization proposal to the Kafka cluster, reassigning partitions to brokers and changing partition leadership.
Caution
|
This is not a dry run. Before you approve an optimization proposal, you must:
|
Procedure
Perform these steps for the optimization proposal that you want to approve.
-
Unless the optimization proposal is newly generated, check that it is based on current information about the state of the Kafka cluster.
To do so, refresh the optimization proposal to make sure it uses the latest cluster metrics:
-
Annotate the KafkaRebalance
resource in Kubernetes with strimzi.io/rebalance=refresh
:
kubectl annotate kafkarebalance <kafka_rebalance_resource_name> strimzi.io/rebalance="refresh"
-
Wait for the status of the optimization proposal to change to ProposalReady
:
kubectl get kafkarebalance -o wide -w -n <namespace>
PendingProposal
-
A PendingProposal
status means the rebalance operator is polling the Cruise Control API to check if the optimization proposal is ready.
ProposalReady
-
A ProposalReady
status means the optimization proposal is ready for review and approval.
When the status changes to ProposalReady
, the optimization proposal is ready to approve.
-
Approve the optimization proposal that you want Cruise Control to apply.
Annotate the KafkaRebalance
resource in Kubernetes with strimzi.io/rebalance=approve
:
kubectl annotate kafkarebalance <kafka_rebalance_resource_name> strimzi.io/rebalance="approve"
-
The Cluster Operator detects the annotated resource and instructs Cruise Control to rebalance the Kafka cluster.
-
Wait for the status of the optimization proposal to change to Ready
:
kubectl get kafkarebalance -o wide -w -n <namespace>
When the status changes to Ready
, the rebalance is complete.
To use the same KafkaRebalance
custom resource to generate another optimization proposal, apply the refresh
annotation to the custom resource.
This moves the custom resource to the PendingProposal
or ProposalReady
state. You can then review the optimization proposal and approve it, if desired.
Once started, a cluster rebalance operation might take some time to complete and affect the overall performance of the Kafka cluster.
If you want to stop a cluster rebalance operation that is in progress, apply the stop
annotation to the KafkaRebalance
custom resource.
This instructs Cruise Control to finish the current batch of partition reassignments and then stop the rebalance.
When the rebalance has stopped, completed partition reassignments have already been applied; therefore, the state of the Kafka cluster is different when compared to prior to the start of the rebalance operation.
If further rebalancing is required, you should generate a new optimization proposal.
Note
|
The performance of the Kafka cluster in the intermediate (stopped) state might be worse than in the initial state.
|
Procedure
-
Annotate the KafkaRebalance
resource in Kubernetes:
kubectl annotate kafkarebalance rebalance-cr-name strimzi.io/rebalance="stop"
-
Check the status of the KafkaRebalance
resource:
kubectl describe kafkarebalance rebalance-cr-name
-
Wait until the status changes to Stopped
.
If an issue occurs when creating a KafkaRebalance
resource or interacting with Cruise Control, the error is reported in the resource status, along with details of how to fix it.
The resource also moves to the NotReady
state.
To continue with the cluster rebalance operation, you must fix the problem in the KafkaRebalance
resource itself or with the overall Cruise Control deployment.
Problems might include the following:
-
A misconfigured parameter in the KafkaRebalance
resource.
-
The strimzi.io/cluster
label for specifying the Kafka cluster in the KafkaRebalance
resource is missing.
-
The Cruise Control server is not deployed as the cruiseControl
property in the Kafka
resource is missing.
-
The Cruise Control server is not reachable.
After fixing the issue, you need to add the refresh
annotation to the KafkaRebalance
resource.
During a “refresh”, a new optimization proposal is requested from the Cruise Control server.
Procedure
-
Get information about the error from the KafkaRebalance
status:
kubectl describe kafkarebalance rebalance-cr-name
-
Attempt to resolve the issue in the KafkaRebalance
resource.
-
Annotate the KafkaRebalance
resource in Kubernetes:
kubectl annotate kafkarebalance rebalance-cr-name strimzi.io/rebalance="refresh"
-
Check the status of the KafkaRebalance
resource:
kubectl describe kafkarebalance rebalance-cr-name
-
Wait until the status changes to PendingProposal
, or directly to ProposalReady
.
Change the replication factor of topics by updating the KafkaTopic
resource managed by the Topic Operator.
You can adjust the replication factor for specific purposes, such as:
The Topic Operator uses Cruise Control to make the necessary changes, so Cruise Control must be deployed with Strimzi.
The Topic Operator watches and periodically reconciles all managed and unpaused KafkaTopic
resources to detect changes to .spec.replicas
configuration by comparing the replication factor of the topic in Kafka.
One or more replication factor updates are then sent to Cruise Control for processing in a single request.
Progress is reflected in the status of the KafkaTopic
resource.
Procedure
-
Edit the KafkaTopic
resource to change the replicas
value.
In this procedure, we change the replicas
value for my-topic
from 1 to 3.
Kafka topic replication factor configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 1
replicas: 3
# ...
-
Apply the change to the KafkaTopic
configuration and wait for the Topic Operator to update the topic.
-
Check the status of the KafkaTopic
resource to make sure the request was successful:
oc get kafkatopics my-topic -o yaml
Status for the replication factor change
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 1
replicas: 3
# ...
# ...
status:
conditions:
- lastTransitionTime: "2024-01-18T16:13:50.490918232Z"
status: "True"
type: Ready
observedGeneration: 2
replicasChange:
sessionId: 1aa418ca-53ed-4b93-b0a4-58413c4fc0cb # (1)
state: ongoing # (2)
targetReplicas: 3 # (3)
topicName: my-topic
-
The session ID for the Cruise Control operation, which is shown when process moves out of a pending state.
-
The state of the update. Moves from pending
to ongoing
, and then the entire replicasChange
status is removed when the change is complete.
-
The requested change to the number of replicas.
An error message is shown in the status if the request fails before completion.
The request is periodically retried if it enters a failed state.
Changing topic replication factor using the standalone Topic Operator
If you are using the standalone Topic Operator and aim to change the topic replication factor through configuration, you still need to use the Topic Operator in unidirectional mode alongside a Cruise Control deployment.
You also need to include the following environment variables in the standalone Topic Operator deployment so that it can integrate with Cruise Control.
Example standalone Topic Operator deployment configuration
apiVersion: apps/v1
kind: Deployment
metadata:
name: strimzi-topic-operator
labels:
app: strimzi
spec:
# ...
template:
# ...
spec:
# ...
containers:
- name: strimzi-topic-operator
# ...
env:
# ...
- name: STRIMZI_CRUISE_CONTROL_ENABLED # (1)
value: true
- name: STRIMZI_CRUISE_CONTROL_RACK_ENABLED # (2)
value: false
- name: STRIMZI_CRUISE_CONTROL_HOSTNAME # (3)
value: cruise-control-api.namespace.svc
- name: STRIMZI_CRUISE_CONTROL_PORT # (4)
value: 9090
- name: STRIMZI_CRUISE_CONTROL_SSL_ENABLED # (5)
value: true
- name: STRIMZI_CRUISE_CONTROL_AUTH_ENABLED # (6)
value: true
-
Integrates Cruise Control with the Topic Operator.
-
Flag to indicate whether rack awareness is enabled on the Kafka cluster. If so, replicas can be spread across different racks, data centers, or availability zones.
-
Cruise Control hostname.
-
Cruise control port.
-
Enables TLS authentication and encryption for accessing the Kafka cluster.
-
Enables basic authorization for accessing the Cruise Control API.
If you enable TLS authentication and authorization, mount the required certificates as follows:
-
Public certificates of the Cluster CA (certificate authority) in /etc/tls-sidecar/cluster-ca-certs/ca.crt
-
Basic authorization credentials (user name and password) in /etc/eto-cc-api/topic-operator.apiAdminName
and /etc/eto-cc-api/topic-operator.apiAdminPassword
You can use the kafka-reassign-partitions.sh
tool for the following:
-
Adding or removing brokers
-
Reassigning partitions across brokers
-
Changing the replication factor of topics
However, while kafka-reassign-partitions.sh
supports these operations, it is generally easier with Cruise Control.
Cruise Control can move topics from one broker to another without any downtime, and it is the most efficient way to reassign partitions.
To use the kafka-reassign-partitions.sh
tool, run it as a separate interactive pod rather than within the broker container.
Running the Kafka bin/
scripts within the broker container may cause a JVM to start with the same settings as the Kafka broker, which can potentially cause disruptions.
By running the kafka-reassign-partitions.sh
tool in a separate pod, you can avoid this issue.
Running a pod with the -ti
option creates an interactive pod with a terminal for running shell commands inside the pod.
Running an interactive pod with a terminal
kubectl run helper-pod -ti --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 --rm=true --restart=Never -- bash
The partition reassignment tool provides the following capabilities for managing Kafka partitions and brokers:
- Redistributing partition replicas
-
Scale your cluster up and down by adding or removing brokers, and move Kafka partitions from heavily loaded brokers to under-utilized brokers.
To do this, you must create a partition reassignment plan that identifies which topics and partitions to move and where to move them.
Cruise Control is recommended for this type of operation as it automates the cluster rebalancing process.
- Scaling topic replication factor up and down
-
Increase or decrease the replication factor of your Kafka topics. To do this, you must create a partition reassignment plan that identifies the existing replication assignment across partitions and an updated assignment with the replication factor changes.
- Changing the preferred leader
-
Change the preferred leader of a Kafka partition.
In Kafka, the partition leader is the only partition that accepts writes from message producers, and therefore has the most complete log across all replicas.
Changing the preferred leader can be useful if you want to redistribute load across the brokers in the cluster.
If the preferred leader is unavailable, another in-sync replica is automatically elected as leader, or the partition goes offline if there are no in-sync replicas.
A background thread moves the leader role to the preferred replica when it is in sync.
Therefore, changing the preferred replicas only makes sense in the context of a cluster rebalancing.
To do this, you must create a partition reassignment plan that specifies the new preferred leader for each partition by changing the order of replicas.
In Kafka’s leader election process, the preferred leader is prioritized by the order of replicas.
The first broker in the order of replicas is designated as the preferred leader.
This designation is important for load balancing by distributing partition leaders across the Kafka cluster.
However, this alone might not be sufficient for optimal load balancing, as some partitions may have higher usage than others.
Cruise Control can help address this by providing more comprehensive cluster rebalancing.
- Changing the log directories to use a specific JBOD volume
-
Change the log directories of your Kafka brokers to use a specific JBOD volume. This can be useful if you want to move your Kafka data to a different disk or storage device. To do this, you must create a partition reassignment plan that specifies the new log directory for each topic.
The partition reassignment tool (kafka-reassign-partitions.sh
) works by generating a partition assignment plan that specifies which partitions should be moved from their current broker to a new broker.
If you are satisfied with the plan, you can execute it.
The tool then does the following:
-
Migrates the partition data to the new broker
-
Updates the metadata on the Kafka brokers to reflect the new partition assignments
-
Triggers a rolling restart of the Kafka brokers to ensure that the new assignments take effect
The partition reassignment tool has three different modes:
--generate
-
Takes a set of topics and brokers and generates a reassignment JSON file which will result in the partitions of those topics being assigned to those brokers.
Because this operates on whole topics, it cannot be used when you only want to reassign some partitions of some topics.
--execute
-
Takes a reassignment JSON file and applies it to the partitions and brokers in the cluster.
Brokers that gain partitions as a result become followers of the partition leader.
For a given partition, once the new broker has caught up and joined the ISR (in-sync replicas) the old broker will stop being a follower and will delete its replica.
--verify
-
Using the same reassignment JSON file as the --execute
step, --verify
checks whether all the partitions in the file have been moved to their intended brokers.
If the reassignment is complete, --verify
also removes any traffic throttles (--throttle
) that are in effect.
Unless removed, throttles will continue to affect the cluster even after the reassignment has finished.
It is only possible to have one reassignment running in a cluster at any given time, and it is not possible to cancel a running reassignment.
If you must cancel a reassignment, wait for it to complete and then perform another reassignment to revert the effects of the first reassignment.
The kafka-reassign-partitions.sh
will print the reassignment JSON for this reversion as part of its output.
Very large reassignments should be broken down into a number of smaller reassignments in case there is a need to stop in-progress reassignment.
The kafka-reassign-partitions.sh
tool uses a reassignment JSON file that specifies the topics to reassign.
You can generate a reassignment JSON file or create a file manually if you want to move specific partitions.
A basic reassignment JSON file has the structure presented in the following example, which describes three partitions belonging to two Kafka topics.
Each partition is reassigned to a new set of replicas, which are identified by their broker IDs.
The version
, topic
, partition
, and replicas
properties are all required.
Example partition reassignment JSON file structure
{
"version": 1, # (1)
"partitions": [ # (2)
{
"topic": "example-topic-1", # (3)
"partition": 0, # (4)
"replicas": [1, 2, 3] # (5)
},
{
"topic": "example-topic-1",
"partition": 1,
"replicas": [2, 3, 4]
},
{
"topic": "example-topic-2",
"partition": 0,
"replicas": [3, 4, 5]
}
]
}
-
The version of the reassignment JSON file format. Currently, only version 1 is supported, so this should always be 1.
-
An array that specifies the partitions to be reassigned.
-
The name of the Kafka topic that the partition belongs to.
-
The ID of the partition being reassigned.
-
An ordered array of the IDs of the brokers that should be assigned as replicas for this partition. The first broker in the list is the leader replica.
Note
|
Partitions not included in the JSON are not changed.
|
If you specify only topics using a topics
array, the partition reassignment tool reassigns all the partitions belonging to the specified topics.
Example reassignment JSON file structure for reassigning all partitions for a topic
{
"version": 1,
"topics": [
{ "topic": "my-topic"}
]
}
When using JBOD storage in your Kafka cluster, you can reassign the partitions between specific volumes and their log directories (each volume has a single log directory).
To reassign a partition to a specific volume, add log_dirs
values for each partition in the reassignment JSON file.
Each log_dirs
array contains the same number of entries as the replicas
array, since each replica should be assigned to a specific log directory.
The log_dirs
array contains either an absolute path to a log directory or the special value any
.
The any
value indicates that Kafka can choose any available log directory for that replica, which can be useful when reassigning partitions between JBOD volumes.
Example reassignment JSON file structure with log directories
{
"version": 1,
"partitions": [
{
"topic": "example-topic-1",
"partition": 0,
"replicas": [1, 2, 3]
"log_dirs": ["/var/lib/kafka/data-0/kafka-log1", "any", "/var/lib/kafka/data-1/kafka-log2"]
},
{
"topic": "example-topic-1",
"partition": 1,
"replicas": [2, 3, 4]
"log_dirs": ["any", "/var/lib/kafka/data-2/kafka-log3", "/var/lib/kafka/data-3/kafka-log4"]
},
{
"topic": "example-topic-2",
"partition": 0,
"replicas": [3, 4, 5]
"log_dirs": ["/var/lib/kafka/data-4/kafka-log5", "any", "/var/lib/kafka/data-5/kafka-log6"]
}
]
}
Partition reassignment can be a slow process because it involves transferring large amounts of data between brokers.
To avoid a detrimental impact on clients, you can throttle the reassignment process.
Use the --throttle
parameter with the kafka-reassign-partitions.sh
tool to throttle a reassignment.
You specify a maximum threshold in bytes per second for the movement of partitions between brokers.
For example, --throttle 5000000
sets a maximum threshold for moving partitions of 50 MBps.
Throttling might cause the reassignment to take longer to complete.
-
If the throttle is too low, the newly assigned brokers will not be able to keep up with records being published and the reassignment will never complete.
-
If the throttle is too high, clients will be impacted.
For example, for producers, this could manifest as higher than normal latency waiting for acknowledgment.
For consumers, this could manifest as a drop in throughput caused by higher latency between polls.
Generate a reassignment JSON file with the kafka-reassign-partitions.sh
tool to reassign partitions after scaling a Kafka cluster.
Adding or removing brokers does not automatically redistribute the existing partitions.
To balance the partition distribution and take full advantage of the new brokers, you can reassign the partitions using the kafka-reassign-partitions.sh
tool.
You run the tool from an interactive pod container connected to the Kafka cluster.
The following procedure describes a secure reassignment process that uses mTLS.
You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.
You’ll need the following to establish a connection:
-
The cluster CA certificate and password generated by the Cluster Operator when the Kafka cluster is created
-
The user CA certificate and password generated by the User Operator when a user is created for client access to the Kafka cluster
In this procedure, the CA certificates and corresponding passwords are extracted from the cluster and user secrets that contain them in PKCS #12 (.p12
and .password
) format.
The passwords allow access to the .p12
stores that contain the certificates.
You use the .p12
stores to specify a truststore and keystore to authenticate connection to the Kafka cluster.
Prerequisites
-
You have a running Cluster Operator.
-
You have a running Kafka cluster based on a Kafka
resource configured with internal TLS encryption and mTLS authentication.
Kafka configuration with TLS encryption and mTLS authentication
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
listeners:
# ...
- name: tls
port: 9093
type: internal
tls: true (1)
authentication:
type: tls (2)
# ...
-
Enables TLS encryption for the internal listener.
-
Listener authentication mechanism specified as mutual tls
.
-
The running Kafka cluster contains a set of topics and partitions to reassign.
Example topic configuration for my-topic
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 10
replicas: 3
config:
retention.ms: 7200000
segment.bytes: 1073741824
# ...
-
You have a KafkaUser
configured with ACL rules that specify permission to produce and consume topics from the Kafka brokers.
Example Kafka user configuration with ACL rules to allow operations on my-topic
and my-cluster
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
name: my-user
labels:
strimzi.io/cluster: my-cluster
spec:
authentication: (1)
type: tls
authorization:
type: simple (2)
acls:
# access to the topic
- resource:
type: topic
name: my-topic
operations:
- Create
- Describe
- Read
- AlterConfigs
host: "*"
# access to the cluster
- resource:
type: cluster
operations:
- Alter
- AlterConfigs
host: "*"
# ...
# ...
-
User authentication mechanism defined as mutual tls
.
-
Simple authorization and accompanying list of ACL rules.
Procedure
-
Extract the cluster CA certificate and password from the <cluster_name>-cluster-ca-cert
secret of the Kafka cluster.
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.p12}' | base64 -d > ca.p12
kubectl get secret <cluster_name>-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 -d > ca.password
Replace <cluster_name> with the name of the Kafka cluster.
When you deploy Kafka using the Kafka
resource, a secret with the cluster CA certificate is created with the Kafka cluster name (<cluster_name>-cluster-ca-cert
).
For example, my-cluster-cluster-ca-cert
.
-
Run a new interactive pod container using the Kafka image to connect to a running Kafka broker.
kubectl run --restart=Never --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 <interactive_pod_name> -- /bin/sh -c "sleep 3600"
Replace <interactive_pod_name> with the name of the pod.
-
Copy the cluster CA certificate to the interactive pod container.
kubectl cp ca.p12 <interactive_pod_name>:/tmp
-
Extract the user CA certificate and password from the secret of the Kafka user that has permission to access the Kafka brokers.
kubectl get secret <kafka_user> -o jsonpath='{.data.user\.p12}' | base64 -d > user.p12
kubectl get secret <kafka_user> -o jsonpath='{.data.user\.password}' | base64 -d > user.password
Replace <kafka_user> with the name of the Kafka user.
When you create a Kafka user using the KafkaUser
resource, a secret with the user CA certificate is created with the Kafka user name.
For example, my-user
.
-
Copy the user CA certificate to the interactive pod container.
kubectl cp user.p12 <interactive_pod_name>:/tmp
The CA certificates allow the interactive pod container to connect to the Kafka broker using TLS.
-
Create a config.properties
file to specify the truststore and keystore used to authenticate connection to the Kafka cluster.
Use the certificates and passwords you extracted in the previous steps.
bootstrap.servers=<kafka_cluster_name>-kafka-bootstrap:9093 (1)
security.protocol=SSL (2)
ssl.truststore.location=/tmp/ca.p12 (3)
ssl.truststore.password=<truststore_password> (4)
ssl.keystore.location=/tmp/user.p12 (5)
ssl.keystore.password=<keystore_password> (6)
-
The bootstrap server address to connect to the Kafka cluster. Use your own Kafka cluster name to replace <kafka_cluster_name>.
-
The security protocol option when using TLS for encryption.
-
The truststore location contains the public key certificate (ca.p12
) for the Kafka cluster.
-
The password (ca.password
) for accessing the truststore.
-
The keystore location contains the public key certificate (user.p12
) for the Kafka user.
-
The password (user.password
) for accessing the keystore.
-
Copy the config.properties
file to the interactive pod container.
kubectl cp config.properties <interactive_pod_name>:/tmp/config.properties
-
Prepare a JSON file named topics.json
that specifies the topics to move.
Specify topic names as a comma-separated list.
Example JSON file to reassign all the partitions of my-topic
{
"version": 1,
"topics": [
{ "topic": "my-topic"}
]
}
-
Copy the topics.json
file to the interactive pod container.
kubectl cp topics.json <interactive_pod_name>:/tmp/topics.json
-
Start a shell process in the interactive pod container.
kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash
Replace <namespace> with the Kubernetes namespace where the pod is running.
-
Use the kafka-reassign-partitions.sh
command to generate the reassignment JSON.
Example command to move the partitions of my-topic
to specified brokers
bin/kafka-reassign-partitions.sh --bootstrap-server my-cluster-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--topics-to-move-json-file /tmp/topics.json \
--broker-list 0,1,2,3,4 \
--generate
Use a reassignment file generated by the kafka-reassign-partitions.sh
tool to reassign partitions after increasing the number of brokers in a Kafka cluster.
The reassignment file should describe how partitions are reassigned to brokers in the enlarged Kafka cluster.
You apply the reassignment specified in the file to the brokers and then verify the new partition assignments.
This procedure describes a secure scaling process that uses TLS.
You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.
The kafka-reassign-partitions.sh
tool can be used to reassign partitions within a Kafka cluster, regardless of whether you are managing all nodes through the cluster or using the node pools to manage groups of nodes within the cluster.
Note
|
Though you can use the kafka-reassign-partitions.sh tool for this operation, Cruise Control is recommended for automated partition reassignments and cluster rebalancing.
Cruise Control can move topics from one broker to another without any downtime, and it is the most efficient way to reassign partitions.
|
Prerequisites
-
You have a running Kafka cluster based on a Kafka
resource configured with internal TLS encryption and mTLS authentication.
-
You have generated a reassignment JSON file named reassignment.json
.
-
You are running an interactive pod container that is connected to the running Kafka broker.
-
You are connected as a KafkaUser
configured with ACL rules that specify permission to manage the Kafka cluster and its topics.
Procedure
-
Add as many new brokers as you need by increasing the Kafka.spec.kafka.replicas
configuration option.
-
Verify that the new broker pods have started.
-
If you haven’t done so, run an interactive pod container to generate a reassignment JSON file named reassignment.json
.
-
Copy the reassignment.json
file to the interactive pod container.
kubectl cp reassignment.json <interactive_pod_name>:/tmp/reassignment.json
Replace <interactive_pod_name> with the name of the pod.
-
Start a shell process in the interactive pod container.
kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash
Replace <namespace> with the Kubernetes namespace where the pod is running.
-
Run the partition reassignment using the kafka-reassign-partitions.sh
script from the interactive pod container.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--execute
Replace <cluster_name> with the name of your Kafka cluster.
For example, my-cluster-kafka-bootstrap:9093
If you are going to throttle replication, you can also pass the --throttle
option with an inter-broker throttled rate in bytes per second. For example:
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--throttle 5000000 \
--execute
This command will print out two reassignment JSON objects.
The first records the current assignment for the partitions being moved.
You should save this to a local file (not a file in the pod) in case you need to revert the reassignment later on.
The second JSON object is the target reassignment you have passed in your reassignment JSON file.
If you need to change the throttle during reassignment, you can use the same command with a different throttled rate. For example:
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--throttle 10000000 \
--execute
-
Verify that the reassignment has completed using the kafka-reassign-partitions.sh
command line tool from any of the broker pods.
This is the same command as the previous step, but with the --verify
option instead of the --execute
option.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--verify
The reassignment has finished when the --verify
command reports that each of the partitions being moved has completed successfully.
This final --verify
will also have the effect of removing any reassignment throttles.
-
You can now delete the revert file if you saved the JSON for reverting the assignment to their original brokers.
Use a reassignment file generated by the kafka-reassign-partitions.sh
tool to reassign partitions before decreasing the number of brokers in a Kafka cluster.
The reassignment file must describe how partitions are reassigned to the remaining brokers in the Kafka cluster.
You apply the reassignment specified in the file to the brokers and then verify the new partition assignments.
Brokers in the highest numbered pods are removed first.
This procedure describes a secure scaling process that uses TLS.
You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.
The kafka-reassign-partitions.sh
tool can be used to reassign partitions within a Kafka cluster, regardless of whether you are managing all nodes through the cluster or using the node pools to manage groups of nodes within the cluster.
Note
|
Though you can use the kafka-reassign-partitions.sh tool for this operation, Cruise Control is recommended for automated partition reassignments and cluster rebalancing.
Cruise Control can move topics from one broker to another without any downtime, and it is the most efficient way to reassign partitions.
|
Prerequisites
-
You have a running Kafka cluster based on a Kafka
resource configured with internal TLS encryption and mTLS authentication.
-
You have generated a reassignment JSON file named reassignment.json
.
-
You are running an interactive pod container that is connected to the running Kafka broker.
-
You are connected as a KafkaUser
configured with ACL rules that specify permission to manage the Kafka cluster and its topics.
Procedure
-
If you haven’t done so, run an interactive pod container to generate a reassignment JSON file named reassignment.json
.
-
Copy the reassignment.json
file to the interactive pod container.
kubectl cp reassignment.json <interactive_pod_name>:/tmp/reassignment.json
Replace <interactive_pod_name> with the name of the pod.
-
Start a shell process in the interactive pod container.
kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash
Replace <namespace> with the Kubernetes namespace where the pod is running.
-
Run the partition reassignment using the kafka-reassign-partitions.sh
script from the interactive pod container.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--execute
Replace <cluster_name> with the name of your Kafka cluster.
For example, my-cluster-kafka-bootstrap:9093
If you are going to throttle replication, you can also pass the --throttle
option with an inter-broker throttled rate in bytes per second. For example:
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--throttle 5000000 \
--execute
This command will print out two reassignment JSON objects.
The first records the current assignment for the partitions being moved.
You should save this to a local file (not a file in the pod) in case you need to revert the reassignment later on.
The second JSON object is the target reassignment you have passed in your reassignment JSON file.
If you need to change the throttle during reassignment, you can use the same command with a different throttled rate. For example:
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--throttle 10000000 \
--execute
-
Verify that the reassignment has completed using the kafka-reassign-partitions.sh
command line tool from any of the broker pods.
This is the same command as the previous step, but with the --verify
option instead of the --execute
option.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--verify
The reassignment has finished when the --verify
command reports that each of the partitions being moved has completed successfully.
This final --verify
will also have the effect of removing any reassignment throttles.
-
You can now delete the revert file if you saved the JSON for reverting the assignment to their original brokers.
-
When all the partition reassignments have finished, the brokers being removed should not have responsibility for any of the partitions in the cluster.
You can verify this by checking that the broker’s data log directory does not contain any live partition logs.
If the log directory on the broker contains a directory that does not match the extended regular expression \.[a-z0-9]-delete$
, the broker still has live partitions and should not be stopped.
You can check this by executing the command:
kubectl exec my-cluster-kafka-0 -c kafka -it -- \
/bin/bash -c \
"ls -l /var/lib/kafka/kafka-log_<n>_ | grep -E '^d' | grep -vE '[a-zA-Z0-9.-]+\.[a-z0-9]+-delete$'"
where n is the number of the pods being deleted.
If the above command prints any output then the broker still has live partitions.
In this case, either the reassignment has not finished or the reassignment JSON file was incorrect.
-
When you have confirmed that the broker has no live partitions, you can edit the Kafka.spec.kafka.replicas
property of your Kafka
resource to reduce the number of brokers.
Use a reassignment file generated by the kafka-reassign-partitions.sh
tool to change the replication factor of topics.
This procedure describes a secure process that uses TLS.
You’ll need a Kafka cluster that uses TLS encryption and mTLS authentication.
Prerequisites
-
You have a running Kafka cluster based on a Kafka
resource configured with internal TLS encryption and mTLS authentication.
-
You are running an interactive pod container that is connected to the running Kafka broker.
-
You have generated a reassignment JSON file named reassignment.json
.
-
You are connected as a KafkaUser
configured with ACL rules that specify permission to manage the Kafka cluster and its topics.
In this procedure, a topic called my-topic
has 4 replicas and we want to reduce it to 3.
A JSON file named topics.json
specifies the topic, and was used to generate the reassignment.json
file.
Example JSON file specifies my-topic
{
"version": 1,
"topics": [
{ "topic": "my-topic"}
]
}
Procedure
-
If you haven’t done so, run an interactive pod container to generate a reassignment JSON file named reassignment.json
.
Example reassignment JSON file showing the current and proposed replica assignment
Current partition replica assignment
{"version":1,"partitions":[{"topic":"my-topic","partition":0,"replicas":[3,4,2,0],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":1,"replicas":[0,2,3,1],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":2,"replicas":[1,3,0,4],"log_dirs":["any","any","any","any"]}]}
Proposed partition reassignment configuration
{"version":1,"partitions":[{"topic":"my-topic","partition":0,"replicas":[0,1,2,3],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":1,"replicas":[1,2,3,4],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":2,"replicas":[2,3,4,0],"log_dirs":["any","any","any","any"]}]}
Save a copy of this file locally in case you need to revert the changes later on.
-
Edit the reassignment.json
to remove a replica from each partition.
Removing the last topic replica for each partition
jq '.partitions[].replicas |= del(.[-1])' reassignment.json > reassignment.json
Example reassignment file showing the updated replicas
{"version":1,"partitions":[{"topic":"my-topic","partition":0,"replicas":[0,1,2],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":1,"replicas":[1,2,3],"log_dirs":["any","any","any","any"]},{"topic":"my-topic","partition":2,"replicas":[2,3,4],"log_dirs":["any","any","any","any"]}]}
-
Copy the reassignment.json
file to the interactive pod container.
kubectl cp reassignment.json <interactive_pod_name>:/tmp/reassignment.json
Replace <interactive_pod_name> with the name of the pod.
-
Start a shell process in the interactive pod container.
kubectl exec -n <namespace> -ti <interactive_pod_name> /bin/bash
Replace <namespace> with the Kubernetes namespace where the pod is running.
-
Make the topic replica change using the kafka-reassign-partitions.sh
script from the interactive pod container.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--execute
Note
|
Removing replicas from a broker does not require any inter-broker data movement, so there is no need to throttle replication.
If you are adding replicas, then you may want to change the throttle rate.
|
-
Verify that the change to the topic replicas has completed using the kafka-reassign-partitions.sh
command line tool from any of the broker pods.
This is the same command as the previous step, but with the --verify
option instead of the --execute
option.
bin/kafka-reassign-partitions.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--reassignment-json-file /tmp/reassignment.json \
--verify
The reassignment has finished when the --verify
command reports that each of the partitions being moved has completed successfully.
This final --verify
will also have the effect of removing any reassignment throttles.
-
Run the bin/kafka-topics.sh
command with the --describe
option to see the results of the change to the topics.
bin/kafka-topics.sh --bootstrap-server
<cluster_name>-kafka-bootstrap:9093 \
--command-config /tmp/config.properties \
--describe
Results of reducing the number of replicas for a topic
my-topic Partition: 0 Leader: 0 Replicas: 0,1,2 Isr: 0,1,2
my-topic Partition: 1 Leader: 2 Replicas: 1,2,3 Isr: 1,2,3
my-topic Partition: 2 Leader: 3 Replicas: 2,3,4 Isr: 2,3,4
-
Finally, edit the KafkaTopic
custom resource to change .spec.replicas
to 3, and then wait the reconciliation.
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 3
replicas: 3
Collecting metrics is critical for understanding the health and performance of your Kafka deployment.
By monitoring metrics, you can actively identify issues before they become critical and make informed decisions about resource allocation and capacity planning. Without metrics, you may be left with limited visibility into the behavior of your Kafka deployment, which can make troubleshooting more difficult and time-consuming. Setting up metrics can save you time and resources in the long run, and help ensure the reliability of your Kafka deployment.
Metrics are available for each component in Strimzi, providing valuable insights into their individual performance.
While other components require configuration to expose metrics, Strimzi operators automatically expose Prometheus metrics by default.
These metrics include:
You can also collect metrics specific to oauth
authentication and opa
or keycloak
authorization by enabling the enableMetrics
property in the listener or authorization configuration of the Kafka
resource.
Similarly, you can enable metrics for oauth
authentication in custom resources such as KafkaBridge
, KafkaConnect
, KafkaMirrorMaker
, and KafkaMirrorMaker2
.
You can use Prometheus and Grafana to monitor Strimzi.
Prometheus consumes metrics from the running pods in your cluster when configured with Prometheus rules.
Grafana visualizes these metrics on dashboards, providing an intuitive interface for monitoring.
To facilitate metrics integration, Strimzi provides example Prometheus rules and Grafana dashboards for Strimzi components.
You can customize the example Grafana dashboards to suit your specific deployment requirements.
You can use rules to define conditions that trigger alerts based on specific metrics.
Depending on your monitoring requirements, you can do the following:
Note
|
Strimzi provides example installation files for Prometheus and Grafana, which can serve as a starting point for monitoring your Strimzi deployment.
For further support, try engaging with the Prometheus and Grafana developer communities.
|
Supporting documentation for metrics and monitoring tools
For more information on the metrics and monitoring tools, refer to the supporting documentation:
Kafka Exporter is an open source project to enhance monitoring of Apache Kafka brokers and clients.
You can configure the Kafka
resource to deploy Kafka Exporter with your Kafka cluster.
Kafka Exporter extracts additional metrics data from Kafka brokers related to offsets, consumer groups, consumer lag, and topics.
The metrics data is used, for example, to help identify slow consumers.
Lag data is exposed as Prometheus metrics, which can then be presented in Grafana for analysis.
Kafka Exporter reads from the __consumer_offsets
topic, which stores information on committed offsets for consumer groups.
For Kafka Exporter to be able to work properly, consumer groups needs to be in use.
Important
|
Kafka Exporter provides only additional metrics related to consumer lag and consumer offsets.
For regular Kafka metrics, you have to configure the Prometheus metrics in Kafka brokers.
|
Consumer lag indicates the difference in the rate of production and consumption of messages.
Specifically, consumer lag for a given consumer group indicates the delay between the last message in the partition and the message being currently picked up by that consumer.
The lag reflects the position of the consumer offset in relation to the end of the partition log.
Consumer lag between the producer and consumer offset
This difference is sometimes referred to as the delta between the producer offset and consumer offset: the read and write positions in the Kafka broker topic partitions.
Suppose a topic streams 100 messages a second. A lag of 1000 messages between the producer offset (the topic partition head) and the last offset the consumer has read means a 10-second delay.
The importance of monitoring consumer lag
For applications that rely on the processing of (near) real-time data, it is critical to monitor consumer lag to check that it does not become too big.
The greater the lag becomes, the further the process moves from the real-time processing objective.
Consumer lag, for example, might be a result of consuming too much old data that has not been purged, or through unplanned shutdowns.
Reducing consumer lag
Use the Grafana charts to analyze lag and to check if actions to reduce lag are having an impact on an affected consumer group.
If, for example, Kafka brokers are adjusted to reduce lag, the dashboard will show the Lag by consumer group chart going down and the Messages consumed per minute chart going up.
Typical actions to reduce lag include:
-
Scaling-up consumer groups by adding new consumers
-
Increasing the retention time for a message to remain in a topic
-
Adding more disk capacity to increase the message buffer
Actions to reduce consumer lag depend on the underlying infrastructure and the use cases Strimzi is supporting.
For instance, a lagging consumer is less likely to benefit from the broker being able to service a fetch request from its disk cache.
And in certain cases, it might be acceptable to automatically drop messages until a consumer has caught up.
Cruise Control monitors Kafka brokers in order to track the utilization of brokers, topics, and partitions.
Cruise Control also provides a set of metrics for monitoring its own performance.
Cruise Control metrics are available for real-time monitoring of Cruise Control operations.
For example, you can use Cruise Control metrics to monitor the status of rebalancing operations that are running or provide alerts on any anomalies that are detected in an operation’s performance.
Cruise Control metrics include a balancedness score.
Balancedness is the measure of how evenly a workload is distributed in a Kafka cluster.
The Cruise Control metric for balancedness score (balancedness-score
) might differ from the balancedness score in the KafkaRebalance
resource.
Cruise Control calculates each score using anomaly.detection.goals
which might not be the same as the default.goals
used in the KafkaRebalance
resource.
The anomaly.detection.goals
are specified in the spec.cruiseControl.config
of the Kafka
custom resource.
Note
|
Refreshing the KafkaRebalance resource fetches an optimization proposal.
The latest cached optimization proposal is fetched if one of the following conditions applies:
Otherwise, Cruise Control generates a new optimization proposal based on KafkaRebalance goals . If new proposals are generated with each refresh, this can impact performance monitoring.
|
Cruise control’s anomaly detector provides metrics data for conditions that block the generation of optimization goals, such as broker failures.
If you want more visibility, you can use the metrics provided by the anomaly detector to set up alerts and send out notifications.
You can set up Cruise Control’s anomaly notifier to route alerts based on these metrics through a specified notification channel.
Alternatively, you can set up Prometheus to scrape the metrics data provided by the anomaly detector and generate alerts.
Prometheus Alertmanager can then route the alerts generated by Prometheus.
Example metrics files provided with Strimzi
metrics
├── grafana-dashboards (1)
│ ├── strimzi-cruise-control.json
│ ├── strimzi-kafka-bridge.json
│ ├── strimzi-kafka-connect.json
│ ├── strimzi-kafka-exporter.json
│ ├── strimzi-kafka-mirror-maker-2.json
│ ├── strimzi-kafka.json
│ ├── strimzi-operators.json
│ └── strimzi-zookeeper.json
├── grafana-install
│ └── grafana.yaml (2)
├── prometheus-additional-properties
│ └── prometheus-additional.yaml (3)
├── prometheus-alertmanager-config
│ └── alert-manager-config.yaml (4)
├── prometheus-install
│ ├── alert-manager.yaml (5)
│ ├── prometheus-rules.yaml (6)
│ ├── prometheus.yaml (7)
│ └── strimzi-pod-monitor.yaml (8)
├── kafka-bridge-metrics.yaml (9)
├── kafka-connect-metrics.yaml (10)
├── kafka-cruise-control-metrics.yaml (11)
├── kafka-metrics.yaml (12)
└── kafka-mirror-maker-2-metrics.yaml (13)
-
Example Grafana dashboards for the different Strimzi components.
-
Installation file for the Grafana image.
-
Additional configuration to scrape metrics for CPU, memory and disk volume usage, which comes directly from the Kubernetes cAdvisor agent and kubelet on the nodes.
-
Hook definitions for sending notifications through Alertmanager.
-
Resources for deploying and configuring Alertmanager.
-
Alerting rules examples for use with Prometheus Alertmanager (deployed with Prometheus).
-
Installation resource file for the Prometheus image.
-
PodMonitor definitions translated by the Prometheus Operator into jobs for the Prometheus server to be able to scrape metrics data directly from pods.
-
Kafka Bridge resource with metrics enabled.
-
Metrics configuration that defines Prometheus JMX Exporter relabeling rules for Kafka Connect.
-
Metrics configuration that defines Prometheus JMX Exporter relabeling rules for Cruise Control.
-
Metrics configuration that defines Prometheus JMX Exporter relabeling rules for Kafka and ZooKeeper.
-
Metrics configuration that defines Prometheus JMX Exporter relabeling rules for Kafka MirrorMaker 2.
Strimzi uses the Prometheus JMX Exporter to expose metrics through an HTTP endpoint, which can be scraped by the Prometheus server.
Grafana dashboards are dependent on Prometheus JMX Exporter relabeling rules, which are defined for Strimzi components in the custom resource configuration.
A label is a name-value pair.
Relabeling is the process of writing a label dynamically.
For example, the value of a label may be derived from the name of a Kafka server and client ID.
Strimzi provides example custom resource configuration YAML files with relabeling rules.
When deploying Prometheus metrics configuration, you can can deploy the example custom resource or copy the metrics configuration to your own custom resource definition.
Table 36. Example custom resources with metrics configuration
Component |
Custom resource |
Example YAML file |
Kafka and ZooKeeper |
Kafka
|
kafka-metrics.yaml
|
Kafka Connect |
KafkaConnect
|
kafka-connect-metrics.yaml
|
Kafka MirrorMaker 2 |
KafkaMirrorMaker2
|
kafka-mirror-maker-2-metrics.yaml
|
Kafka Bridge |
KafkaBridge
|
kafka-bridge-metrics.yaml
|
Cruise Control |
Kafka
|
kafka-cruise-control-metrics.yaml
|
The prometheus-rules.yaml
file contains example rules for the following components:
-
Kafka
-
ZooKeeper
-
Entity Operator
-
Kafka Connect
-
Kafka Bridge
-
MirrorMaker
-
Kafka Exporter
A description of each of the example rules is provided in the file.
Alerting rules provide notifications about specific conditions observed in metrics.
Rules are declared on the Prometheus server, but Prometheus Alertmanager is responsible for alert notifications.
Prometheus alerting rules describe conditions using PromQL expressions that are continuously evaluated.
When an alert expression becomes true, the condition is met and the Prometheus server sends alert data to the Alertmanager.
Alertmanager then sends out a notification using the communication method configured for its deployment.
General points about the alerting rule definitions:
-
A for
property is used with the rules to determine the period of time a condition must persist before an alert is triggered.
-
A tick is a basic ZooKeeper time unit, which is measured in milliseconds and configured using the tickTime
parameter of Kafka.spec.zookeeper.config
. For example, if ZooKeeper tickTime=3000
, 3 ticks (3 x 3000) equals 9000 milliseconds.
-
The availability of the ZookeeperRunningOutOfSpace
metric and alert is dependent on the Kubernetes configuration and storage implementation used. Storage implementations for certain platforms may not be able to supply the information on available space required for the metric to provide an alert.
Alertmanager can be configured to use email, chat messages or other notification methods.
Adapt the default configuration of the example rules according to your specific needs.
If you deploy Prometheus to provide metrics,
you can use the example Grafana dashboards provided with Strimzi to monitor Strimzi components.
Example dashboards are provided in the examples/metrics/grafana-dashboards
directory as JSON files.
All dashboards provide JVM metrics, as well as metrics specific to the component.
For example, the Grafana dashboard for Strimzi operators provides information on the number of reconciliations or custom resources they are processing.
The example dashboards don’t show all the metrics supported by Kafka.
The dashboards are populated with a representative set of metrics for monitoring.
Table 37. Example Grafana dashboard files
Component |
Example JSON file |
Strimzi operators |
strimzi-operators.json
|
Kafka |
strimzi-kafka.json
|
ZooKeeper |
strimzi-zookeeper.json
|
Kafka Connect |
strimzi-kafka-connect.json
|
Kafka MirrorMaker 2 |
strimzi-kafka-mirror-maker-2.json
|
Kafka Bridge |
strimzi-kafka-bridge.json
|
Cruise Control |
strimzi-cruise-control.json
|
Kafka Exporter |
strimzi-kafka-exporter.json
|
Note
|
When metrics are not available to the Kafka Exporter, because there is no traffic in the cluster yet, the Kafka Exporter Grafana dashboard will show N/A for numeric fields and No data to show for graphs.
|
You can use Prometheus to provide monitoring data for the example Grafana dashboards provided with Strimzi.
To expose metrics in Prometheus format, you add configuration to a custom resource.
You must also make sure that the metrics are scraped by your monitoring stack.
Prometheus and Prometheus Alertmanager are used in the examples provided by Strimzi, but you can use also other compatible tools.
Using Prometheus with Strimzi, requires the following:
To enable and expose metrics in Strimzi for Prometheus, use metrics configuration properties.
The following components require metricsConfig
configuration to expose metrics:
-
Kafka
-
KafkaConnect
-
MirrorMaker
-
Cruise Control
-
ZooKeeper
This configuration enables the Prometheus JMX Exporter to expose metrics through an HTTP endpoint.
The port for the JMX exporter HTTP endpoint is 9404.
Prometheus scrapes this endpoint to collect Kafka metrics.
Set the enableMetrics
property to true
in order to expose metrics for these components:
-
kafka-metrics.yaml
-
kafka-connect-metrics.yaml
-
kafka-mirror-maker-2-metrics.yaml
-
kafka-bridge-metrics.yaml
-
kafka-cruise-control-metrics.yaml
-
oauth-metrics.yaml
These files contain the necessary relabeling rules and configuration to enable Prometheus metrics.
They are a good starting point for trying Prometheus with Strimzi.
This procedure shows how to deploy example Prometheus metrics configuration in the Kafka
resource.
The process is the same when deploying the example files for other resources.
If you wish to include Kafka Exporter metrics, add kafkaExporter
configuration to your Kafka
resource.
Important
|
Kafka Exporter only provides additional metrics related to consumer lag and consumer offsets.
For regular Kafka metrics, configure Prometheus metrics in the Kafka resource.
|
Procedure
-
Deploy the example custom resource with the Prometheus configuration.
For example, for each Kafka
resource you can apply the kafka-metrics.yaml
file.
Deploying the example configuration
kubectl apply -f kafka-metrics.yaml
Alternatively, copy the example configuration in kafka-metrics.yaml
to your own Kafka
resource.
Copying the example configuration
kubectl edit kafka <kafka_configuration_file>
Copy the metricsConfig
property and the ConfigMap
it references to your Kafka
resource.
Example metrics configuration for Kafka
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
# ...
metricsConfig: (1)
type: jmxPrometheusExporter
valueFrom:
configMapKeyRef:
name: kafka-metrics
key: kafka-metrics-config.yml
---
kind: ConfigMap (2)
apiVersion: v1
metadata:
name: kafka-metrics
labels:
app: strimzi
data:
kafka-metrics-config.yml: |
# metrics configuration...
-
Copy the metricsConfig
property that references the ConfigMap
containing metrics configuration.
-
Copy the whole ConfigMap
specifying the metrics configuration.
-
To deploy Kafka Exporter, add kafkaExporter
configuration.
kafkaExporter
configuration is specified only in the Kafka
resource.
Example configuration for deploying Kafka Exporter
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
# ...
kafkaExporter:
image: my-registry.io/my-org/my-exporter-cluster:latest # (1)
groupRegex: ".*" # (2)
topicRegex: ".*" # (3)
groupExcludeRegex: "^excluded-.*" # (4)
topicExcludeRegex: "^excluded-.*" # (5)
showAllOffsets: false # (6)
resources: # (7)
requests:
cpu: 200m
memory: 64Mi
limits:
cpu: 500m
memory: 128Mi
logging: debug # (8)
enableSaramaLogging: true # (9)
template: # (10)
pod:
metadata:
labels:
label1: value1
imagePullSecrets:
- name: my-docker-credentials
securityContext:
runAsUser: 1000001
fsGroup: 0
terminationGracePeriodSeconds: 120
readinessProbe: # (11)
initialDelaySeconds: 15
timeoutSeconds: 5
livenessProbe: # (12)
initialDelaySeconds: 15
timeoutSeconds: 5
# ...
-
ADVANCED OPTION: Container image configuration, which is recommended only in special situations.
-
A regular expression to specify the consumer groups to include in the metrics.
-
A regular expression to specify the topics to include in the metrics.
-
A regular expression to specify the consumer groups to exclude in the metrics.
-
A regular expression to specify the topics to exclude in the metrics.
-
By default, metrics are collected for all consumers regardless of their connection status. Setting showAllOffsets
to false
stops collecting metrics on disconnected consumers.
-
CPU and memory resources to reserve.
-
Logging configuration, to log messages with a given severity (debug, info, warn, error, fatal) or above.
-
Boolean to enable Sarama logging, a Go client library used by Kafka Exporter.
-
Customization of deployment templates and pods.
-
Healthcheck readiness probes.
-
Healthcheck liveness probes.
Note
|
For Kafka Exporter to be able to work properly, consumer groups need to be in use.
|
Enabling metrics for Kafka Bridge
To expose metrics for Kafka Bridge, set the enableMetrics
property to true
in the KafkaBridge
resource.
Example metrics configuration for Kafka Bridge
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
bootstrapServers: my-cluster-kafka:9092
http:
# ...
enableMetrics: true
# ...
Enabling metrics for OAuth 2.0 and OPA
To expose metrics for OAuth 2.0 or OPA, set the enableMetrics
property to true
in the appropriate custom resource.
- OAuth 2.0 metrics
-
Enable metrics for Kafka cluster authorization and Kafka listener authentication in the Kafka
resource.
You can also enable metrics for OAuth 2.0 authentication in the custom resource of other supported components.
- OPA metrics
-
Enable metrics for Kafka cluster authorization in the Kafka
resource similar to OAuth 2.0.
In the following example, metrics are enabled for OAuth 2.0 listener authentication and OAuth 2.0 (keycloak
) cluster authorization.
Example cluster configuration with metrics enabled for OAuth 2.0
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
listeners:
- name: external3
port: 9094
type: loadbalancer
tls: true
authentication:
type: oauth
enableMetrics: true
configuration:
#...
authorization:
type: keycloak
enableMetrics: true
# ...
To use OAuth 2.0 metrics with Prometheus, copy the ConfigMap
configuration from the oauth-metrics.yaml
file to the same Kafka
resource configuration file where you enabled metrics for OAuth 2.0 and then apply the configuration.
Prometheus provides an open source set of components for systems monitoring and alert notification.
We describe here how you can use the CoreOS Prometheus Operator to run and manage a Prometheus server that is suitable for use in production environments, but with the correct configuration you can run any Prometheus server.
Note
|
The Prometheus server configuration uses service discovery to discover the pods in the cluster from which it gets metrics. For this feature to work correctly, the service account used for running the Prometheus service pod must have access to the API server so it can retrieve the pod list.
|
A Prometheus YAML file is provided for deployment:
Additional Prometheus-related configuration is also provided in the following files:
For Prometheus to obtain monitoring data:
Then use the configuration files to:
When you apply the Prometheus configuration, the following resources are created in your Kubernetes cluster and managed by the Prometheus Operator:
-
A ClusterRole
that grants permissions to Prometheus to read the health endpoints exposed by the Kafka and ZooKeeper pods, cAdvisor and the kubelet for container metrics.
-
A ServiceAccount
for the Prometheus pods to run under.
-
A ClusterRoleBinding
which binds the ClusterRole
to the ServiceAccount
.
-
A Deployment
to manage the Prometheus Operator pod.
-
A PodMonitor
to manage the configuration of the Prometheus pod.
-
A Prometheus
to manage the configuration of the Prometheus pod.
-
A PrometheusRule
to manage alerting rules for the Prometheus pod.
-
A Secret
to manage additional Prometheus settings.
-
A Service
to allow applications running in the cluster to connect to Prometheus (for example, Grafana using Prometheus as datasource).
Procedure
-
Download the bundle.yaml
resources file from the repository:
curl -s https://raw.githubusercontent.com/coreos/prometheus-operator/master/bundle.yaml > prometheus-operator-deployment.yaml
-
Use the latest master
release as shown, or choose a release that is compatible with your version of Kubernetes (see the Kubernetes compatibility matrix).
The master
release of the Prometheus Operator works with Kubernetes 1.18+.
-
Update the namespace by replacing the example my-namespace
with your own.
sed -E -i '/[[:space:]]*namespace: [a-zA-Z0-9-]*$/s/namespace:[[:space:]]*[a-zA-Z0-9-]*$/namespace: my-namespace/' prometheus-operator-deployment.yaml
sed -i '' -e '/[[:space:]]*namespace: [a-zA-Z0-9-]*$/s/namespace:[[:space:]]*[a-zA-Z0-9-]*$/namespace: my-namespace/' prometheus-operator-deployment.yaml
Note
|
If using OpenShift, specify a release of the OpenShift fork of the Prometheus Operator repository.
|
-
(Optional) If it is not required, you can manually remove the spec.template.spec.securityContext
property from the prometheus-operator-deployment.yaml
file.
-
Deploy the Prometheus Operator:
kubectl create -f prometheus-operator-deployment.yaml
Use Prometheus to obtain monitoring data in your Kafka cluster.
You can use your own Prometheus deployment or deploy Prometheus using the example metrics configuration files provided by Strimzi.
The example files include a configuration file for a Prometheus deployment and files for Prometheus-related resources:
-
examples/metrics/prometheus-install/prometheus.yaml
-
examples/metrics/prometheus-install/prometheus-rules.yaml
-
examples/metrics/prometheus-install/strimzi-pod-monitor.yaml
-
examples/metrics/prometheus-additional-properties/prometheus-additional.yaml
The deployment process creates a ClusterRoleBinding
and discovers an Alertmanager instance in the namespace specified for the deployment.
Note
|
By default, the Prometheus Operator only supports jobs that include an endpoints role for service discovery. Targets are discovered and scraped for each endpoint port address. For endpoint discovery, the port address may be derived from service (role: service ) or pod (role: pod ) discovery.
|
Procedure
-
Modify the Prometheus installation file (prometheus.yaml
) according to the namespace Prometheus is going to be installed into:
sed -i 's/namespace: .*/namespace: my-namespace/' prometheus.yaml
sed -i '' 's/namespace: .*/namespace: my-namespace/' prometheus.yaml
-
Edit the PodMonitor
resource in strimzi-pod-monitor.yaml
to define Prometheus jobs that will scrape the metrics data from pods.
Update the namespaceSelector.matchNames
property with the namespace where the pods to scrape the metrics from are running.
PodMonitor
is used to scrape data directly from pods for Apache Kafka, ZooKeeper, Operators, the Kafka Bridge and Cruise Control.
-
Edit the prometheus.yaml
installation file to include additional configuration for scraping metrics directly from nodes.
The Grafana dashboards provided show metrics for CPU, memory and disk volume usage, which come directly from the Kubernetes cAdvisor agent and kubelet on the nodes.
The Prometheus Operator does not have a monitoring resource like PodMonitor
for scraping the nodes, so the prometheus-additional.yaml
file contains the additional configuration needed.
-
Create a Secret
resource from the configuration file (prometheus-additional.yaml
in the examples/metrics/prometheus-additional-properties
directory):
kubectl apply -f prometheus-additional.yaml
-
Edit the additionalScrapeConfigs
property in the prometheus.yaml
file to include the name of the Secret
in the prometheus-additional.yaml
file.
-
Deploy the Prometheus resources:
kubectl apply -f strimzi-pod-monitor.yaml
kubectl apply -f prometheus-rules.yaml
kubectl apply -f prometheus.yaml
Use Alertmanager to route alerts to a notification service.
Prometheus Alertmanager is a component for handling alerts and routing them to a notification service.
Alertmanager supports an essential aspect of monitoring, which is to be notified of conditions that indicate potential issues based on alerting rules.
You can use the example metrics configuration files provided by Strimzi to deploy Alertmanager to send notifications to a Slack channel.
A configuration file defines the resources for deploying Alertmanager:
An additional configuration file provides the hook definitions for sending notifications from your Kafka cluster:
The following resources are defined on deployment:
-
An Alertmanager
to manage the Alertmanager pod.
-
A Secret
to manage the configuration of the Alertmanager.
-
A Service
to provide an easy to reference hostname for other services to connect to Alertmanager (such as Prometheus).
Procedure
-
Update the alert-manager-config.yaml
file in the examples/metrics/prometheus-alertmanager-config
directory to replace the following:
-
Create a Secret
resource from the Alertmanager configuration file:
kubectl apply -f alert-manager-config.yaml
-
Deploy Alertmanager:
kubectl apply -f alert-manager.yaml
Use Grafana to provide visualizations of Prometheus metrics on customizable dashboards.
You can use your own Grafana deployment or deploy Grafana using the example metrics configuration files provided by Strimzi.
The example files include a configuration file for a Grafana deployment
This procedure uses the example Grafana configuration file and example dashboards.
The example dashboards are a good starting point for monitoring key metrics, but they don’t show all the metrics supported by Kafka.
You can modify the example dashboards or add other metrics, depending on your infrastructure.
Note
|
No alert notification rules are defined.
|
When accessing a dashboard, you can use the port-forward
command to forward traffic from the Grafana pod to the host.
The name of the Grafana pod is different for each user.
Procedure
-
Deploy Grafana.
kubectl apply -f grafana.yaml
-
Get the details of the Grafana service.
kubectl get service grafana
NAME |
TYPE |
CLUSTER-IP |
PORT(S) |
grafana |
ClusterIP |
172.30.123.40 |
3000/TCP |
Note the port number for port forwarding.
-
Use port-forward
to redirect the Grafana user interface to localhost:3000
:
kubectl port-forward svc/grafana 3000:3000
-
In a web browser, access the Grafana login screen using the URL http://localhost:3000
.
The Grafana Log In page appears.
-
Enter your user name and password, and then click Log In.
The default Grafana user name and password are both admin
. After logging in for the first time, you can change the password.
-
In Configuration > Data Sources, add Prometheus as a data source.
-
Click the + icon and then click Import.
-
In examples/metrics/grafana-dashboards
, copy the JSON of the dashboard to import.
-
Paste the JSON into the text box, and then click Load.
-
Repeat steps 7-9 for the other example Grafana dashboards.
The imported Grafana dashboards are available to view from the Dashboards home page.
Distributed tracing tracks the progress of transactions between applications in a distributed system.
In a microservices architecture, tracing tracks the progress of transactions between services.
Trace data is useful for monitoring application performance and investigating issues with target systems and end-user applications.
In Strimzi, tracing facilitates the end-to-end tracking of messages: from source systems to Kafka, and then from Kafka to target systems and applications.
Distributed tracing complements the monitoring of metrics in Grafana dashboards, as well as the component loggers.
Support for tracing is built in to the following Kafka components:
-
MirrorMaker to trace messages from a source cluster to a target cluster
-
Kafka Connect to trace messages consumed and produced by Kafka Connect
-
Kafka Bridge to trace messages between Kafka and HTTP client applications
Tracing is not supported for Kafka brokers.
You enable and configure tracing for these components through their custom resources.
You add tracing configuration using spec.template
properties.
You enable tracing by specifying a tracing type using the spec.tracing.type
property:
opentelemetry
-
Specify type: opentelemetry
to use OpenTelemetry. By Default, OpenTelemetry uses the OTLP (OpenTelemetry Protocol) exporter and endpoint to get trace data. You can specify other tracing systems supported by OpenTelemetry, including Jaeger tracing. To do this, you change the OpenTelemetry exporter and endpoint in the tracing configuration.
Caution
|
Strimzi no longer supports OpenTracing.
If you were previously using OpenTracing with the type: jaeger option, we encourage you to transition to using OpenTelemetry instead.
|
Use OpenTelemetry with the Jaeger tracing system.
OpenTelemetry provides an API specification that is independent from the tracing or monitoring system.
You use the APIs to instrument application code for tracing.
Jaeger is a tracing system for microservices-based distributed systems.
The Jaeger user interface showing a simple query
Use environment variables when you are enabling tracing for Kafka components or initializing a tracer for Kafka clients.
The following tables describe the key environment variables for setting up a tracer.
Table 38. OpenTelemetry environment variables
Property |
Required |
Description |
OTEL_SERVICE_NAME
|
Yes |
The name of the Jaeger tracing service for OpenTelemetry. |
OTEL_EXPORTER_JAEGER_ENDPOINT
|
Yes |
The exporter used for tracing. |
OTEL_TRACES_EXPORTER
|
Yes |
The exporter used for tracing.
Set to otlp by default. If using Jaeger tracing, you need to set this environment variable as jaeger .
If you are using another tracing implementation, specify the exporter used. |
Enable distributed tracing in Kafka components by specifying a tracing type in the custom resource.
Instrument tracers in Kafka clients for end-to-end tracking of messages.
To set up distributed tracing, follow these procedures in order:
Before setting up distributed tracing, make sure Jaeger backend components are deployed to your Kubernetes cluster.
We recommend using the Jaeger operator for deploying Jaeger on your Kubernetes cluster.
Note
|
Setting up tracing for applications and systems beyond Strimzi is outside the scope of this content.
|
Distributed tracing is supported for MirrorMaker, MirrorMaker 2, Kafka Connect, and the Kafka Bridge.
Configure the custom resource of the component to specify and enable a tracer service.
Enabling tracing in a resource triggers the following events:
-
Interceptor classes are updated in the integrated consumers and producers of the component.
-
For MirrorMaker, MirrorMaker 2, and Kafka Connect, the tracing agent initializes a tracer based on the tracing configuration defined in the resource.
-
For the Kafka Bridge, a tracer based on the tracing configuration defined in the resource is initialized by the Kafka Bridge itself.
You can enable tracing that uses OpenTelemetry.
Tracing in MirrorMaker and MirrorMaker 2
For MirrorMaker and MirrorMaker 2, messages are traced from the source cluster to the target cluster. The trace data records messages entering and leaving the MirrorMaker or MirrorMaker 2 component.
Tracing in Kafka Connect
For Kafka Connect, only messages produced and consumed by Kafka Connect are traced. To trace messages sent between Kafka Connect and external systems, you must configure tracing in the connectors for those systems.
Tracing in the Kafka Bridge
For the Kafka Bridge, messages produced and consumed by the Kafka Bridge are traced. Incoming HTTP requests from client applications to send and receive messages through the Kafka Bridge are also traced.
To have end-to-end tracing, you must configure tracing in your HTTP clients.
Procedure
Perform these steps for each KafkaMirrorMaker
, KafkaMirrorMaker2
, KafkaConnect
, and KafkaBridge
resource.
-
In the spec.template
property, configure the tracer service.
-
Use the tracing environment variables as template configuration properties.
-
For OpenTelemetry, set the spec.tracing.type
property to opentelemetry
.
Example tracing configuration for Kafka Connect using OpenTelemetry
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect-cluster
spec:
#...
template:
connectContainer:
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing:
type: opentelemetry
#...
Example tracing configuration for MirrorMaker using OpenTelemetry
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker
metadata:
name: my-mirror-maker
spec:
#...
template:
mirrorMakerContainer:
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing:
type: opentelemetry
#...
Example tracing configuration for MirrorMaker 2 using OpenTelemetry
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mm2-cluster
spec:
#...
template:
connectContainer:
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing:
type: opentelemetry
#...
Example tracing configuration for the Kafka Bridge using OpenTelemetry
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
#...
template:
bridgeContainer:
env:
- name: OTEL_SERVICE_NAME
value: my-otel-service
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: "http://otlp-host:4317"
tracing:
type: opentelemetry
#...
-
Create or update the resource:
kubectl apply -f <resource_configuration_file>
Initialize a tracer for OpenTelemetry, then instrument your client applications for distributed tracing.
You can instrument Kafka producer and consumer clients, and Kafka Streams API applications.
Procedure
In each client application add the dependencies for the tracer:
-
Add the Maven dependencies to the pom.xml
file for the client application:
Dependencies for OpenTelemetry
<dependency>
<groupId>io.opentelemetry.semconv</groupId>
<artifactId>opentelemetry-semconv</artifactId>
<version>1.21.0-alpha</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
<version>1.34.1</version>
<exclusions>
<exclusion>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-sender-okhttp</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-sender-grpc-managed-channel</artifactId>
<version>1.34.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk-extension-autoconfigure</artifactId>
<version>1.34.1</version>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-kafka-clients-2.6</artifactId>
<version>1.32.0-alpha</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
<version>1.34.1</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-sender-jdk</artifactId>
<version>1.34.1-alpha</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.61.0</version>
</dependency>
-
Define the configuration of the tracer using the tracing environment variables.
-
Create a tracer, which is initialized with the environment variables:
Creating a tracer for OpenTelemetry
OpenTelemetry ot = GlobalOpenTelemetry.get();
-
Register the tracer as a global tracer:
GlobalTracer.register(tracer);
-
Instrument your client:
Instrument application code to enable tracing in Kafka producers and consumers.
Use a decorator pattern or interceptors to instrument your Java producer and consumer application code for tracing.
You can then record traces when messages are produced or retrieved from a topic.
OpenTelemetry instrumentation project provides classes that support instrumentation of producers and consumers.
- Decorator instrumentation
-
For decorator instrumentation, create a modified producer or consumer instance for tracing.
- Interceptor instrumentation
-
For interceptor instrumentation, add the tracing capability to the consumer or producer configuration.
Procedure
Perform these steps in the application code of each producer and consumer application.
Instrument your client application code using either a decorator pattern or interceptors.
-
To use a decorator pattern, create a modified producer or consumer instance to send or receive messages.
You pass the original KafkaProducer
or KafkaConsumer
class.
Example decorator instrumentation for OpenTelemetry
// Producer instance
Producer < String, String > op = new KafkaProducer < > (
configs,
new StringSerializer(),
new StringSerializer()
);
Producer < String, String > producer = tracing.wrap(op);
KafkaTracing tracing = KafkaTracing.create(GlobalOpenTelemetry.get());
producer.send(...);
//consumer instance
Consumer<String, String> oc = new KafkaConsumer<>(
configs,
new StringDeserializer(),
new StringDeserializer()
);
Consumer<String, String> consumer = tracing.wrap(oc);
consumer.subscribe(Collections.singleton("mytopic"));
ConsumerRecords<Integer, String> records = consumer.poll(1000);
ConsumerRecord<Integer, String> record = ...
SpanContext spanContext = TracingKafkaUtils.extractSpanContext(record.headers(), tracer);
-
To use interceptors, set the interceptor class in the producer or consumer configuration.
You use the KafkaProducer
and KafkaConsumer
classes in the usual way.
The TracingProducerInterceptor
and TracingConsumerInterceptor
interceptor classes take care of the tracing capability.
Example producer configuration using interceptors
senderProps.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,
TracingProducerInterceptor.class.getName());
KafkaProducer<Integer, String> producer = new KafkaProducer<>(senderProps);
producer.send(...);
Example consumer configuration using interceptors
consumerProps.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG,
TracingConsumerInterceptor.class.getName());
KafkaConsumer<Integer, String> consumer = new KafkaConsumer<>(consumerProps);
consumer.subscribe(Collections.singletonList("messages"));
ConsumerRecords<Integer, String> records = consumer.poll(1000);
ConsumerRecord<Integer, String> record = ...
SpanContext spanContext = TracingKafkaUtils.extractSpanContext(record.headers(), tracer);
Instrument application code to enable tracing in Kafka Streams API applications.
Use a decorator pattern or interceptors to instrument your Kafka Streams API applications for tracing.
You can then record traces when messages are produced or retrieved from a topic.
- Decorator instrumentation
-
For decorator instrumentation, create a modified Kafka Streams instance for tracing.
For OpenTelemetry, you need to create a custom TracingKafkaClientSupplier
class to provide tracing instrumentation for Kafka Streams.
- Interceptor instrumentation
-
For interceptor instrumentation, add the tracing capability to the Kafka Streams producer and consumer configuration.
Prerequisites
-
You have initialized tracing for the client.
You enable instrumentation in Kafka Streams applications by adding the tracing JARs as dependencies to your project.
-
To instrument Kafka Streams with OpenTelemetry, you’ll need to write a custom TracingKafkaClientSupplier
.
-
The custom TracingKafkaClientSupplier
can extend Kafka’s DefaultKafkaClientSupplier
, overriding the producer and consumer creation methods to wrap the instances with the telemetry-related code.
Example custom TracingKafkaClientSupplier
private class TracingKafkaClientSupplier extends DefaultKafkaClientSupplier {
@Override
public Producer<byte[], byte[]> getProducer(Map<String, Object> config) {
KafkaTelemetry telemetry = KafkaTelemetry.create(GlobalOpenTelemetry.get());
return telemetry.wrap(super.getProducer(config));
}
@Override
public Consumer<byte[], byte[]> getConsumer(Map<String, Object> config) {
KafkaTelemetry telemetry = KafkaTelemetry.create(GlobalOpenTelemetry.get());
return telemetry.wrap(super.getConsumer(config));
}
@Override
public Consumer<byte[], byte[]> getRestoreConsumer(Map<String, Object> config) {
return this.getConsumer(config);
}
@Override
public Consumer<byte[], byte[]> getGlobalConsumer(Map<String, Object> config) {
return this.getConsumer(config);
}
}
Procedure
Perform these steps for each Kafka Streams API application.
-
To use a decorator pattern, create an instance of the TracingKafkaClientSupplier
supplier interface, then provide the supplier interface to KafkaStreams
.
Example decorator instrumentation
KafkaClientSupplier supplier = new TracingKafkaClientSupplier(tracer);
KafkaStreams streams = new KafkaStreams(builder.build(), new StreamsConfig(config), supplier);
streams.start();
-
To use interceptors, set the interceptor class in the Kafka Streams producer and consumer configuration.
The TracingProducerInterceptor
and TracingConsumerInterceptor
interceptor classes take care of the tracing capability.
Example producer and consumer configuration using interceptors
props.put(StreamsConfig.PRODUCER_PREFIX + ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, TracingProducerInterceptor.class.getName());
props.put(StreamsConfig.CONSUMER_PREFIX + ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, TracingConsumerInterceptor.class.getName());
Instead of the default OTLP system, you can specify other tracing systems that are supported by OpenTelemetry.
You do this by adding the required artifacts to the Kafka image provided with Strimzi.
Any required implementation specific environment variables must also be set.
You then enable the new tracing implementation using the OTEL_TRACES_EXPORTER
environment variable.
This procedure shows how to implement Zipkin tracing.
Procedure
-
Add the tracing artifacts to the /opt/kafka/libs/
directory of the Kafka image.
You can use the Kafka container image on the Container Registry as a base image for creating a new custom image.
OpenTelemetry artifact for Zipkin
io.opentelemetry:opentelemetry-exporter-zipkin
-
Set the tracing exporter and endpoint for the new tracing implementation.
Example Zikpin tracer configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mm2-cluster
spec:
#...
template:
connectContainer:
env:
- name: OTEL_SERVICE_NAME
value: my-zipkin-service
- name: OTEL_EXPORTER_ZIPKIN_ENDPOINT
value: http://zipkin-exporter-host-name:9411/api/v2/spans # (1)
- name: OTEL_TRACES_EXPORTER
value: zipkin # (2)
tracing:
type: opentelemetry
#...
-
Specifies the Zipkin endpoint to connect to.
-
The Zipkin exporter.
A tracing span is a logical unit of work in Jaeger, with an operation name, start time, and duration.
Spans have built-in names, but you can specify custom span names in your Kafka client instrumentation where used.
Custom span names cannot be specified directly with OpenTelemetry.
Instead, you retrieve span names by adding code to your client application to extract additional tags and attributes.
Example code to extract attributes
//Defines attribute extraction for a producer
private static class ProducerAttribExtractor implements AttributesExtractor < ProducerRecord < ? , ? > , Void > {
@Override
public void onStart(AttributesBuilder attributes, ProducerRecord < ? , ? > producerRecord) {
set(attributes, AttributeKey.stringKey("prod_start"), "prod1");
}
@Override
public void onEnd(AttributesBuilder attributes, ProducerRecord < ? , ? > producerRecord, @Nullable Void unused, @Nullable Throwable error) {
set(attributes, AttributeKey.stringKey("prod_end"), "prod2");
}
}
//Defines attribute extraction for a consumer
private static class ConsumerAttribExtractor implements AttributesExtractor < ConsumerRecord < ? , ? > , Void > {
@Override
public void onStart(AttributesBuilder attributes, ConsumerRecord < ? , ? > producerRecord) {
set(attributes, AttributeKey.stringKey("con_start"), "con1");
}
@Override
public void onEnd(AttributesBuilder attributes, ConsumerRecord < ? , ? > producerRecord, @Nullable Void unused, @Nullable Throwable error) {
set(attributes, AttributeKey.stringKey("con_end"), "con2");
}
}
//Extracts the attributes
public static void main(String[] args) throws Exception {
Map < String, Object > configs = new HashMap < > (Collections.singletonMap(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"));
System.setProperty("otel.traces.exporter", "jaeger");
System.setProperty("otel.service.name", "myapp1");
KafkaTracing tracing = KafkaTracing.newBuilder(GlobalOpenTelemetry.get())
.addProducerAttributesExtractors(new ProducerAttribExtractor())
.addConsumerAttributesExtractors(new ConsumerAttribExtractor())
.build();
Kafka and ZooKeeper pods might be evicted during Kubernetes upgrades, maintenance, or pod rescheduling.
If your Kafka and ZooKeeper pods were deployed by Strimzi, you can use the Strimzi Drain Cleaner tool to handle the pod evictions.
The Strimzi Drain Cleaner handles the eviction instead of Kubernetes.
By deploying the Strimzi Drain Cleaner, you can use the Cluster Operator to move Kafka pods instead of Kubernetes.
The Cluster Operator ensures that the number of in sync replicas for topics are at or above the configured min.insync.replicas
and Kafka can remain operational during the eviction process.
The Cluster Operator waits for topics to synchronize, as the Kubernetes worker nodes drain consecutively.
An admission webhook notifies the Strimzi Drain Cleaner of pod eviction requests to the Kubernetes API.
The Strimzi Drain Cleaner then adds a rolling update annotation to the pods to be drained.
This informs the Cluster Operator to perform a rolling update of an evicted pod.
Webhook configuration
The Strimzi Drain Cleaner deployment files include a ValidatingWebhookConfiguration
resource file.
The resource provides the configuration for registering the webhook with the Kubernetes API.
The configuration defines the rules
for the Kubernetes API to follow in the event of a pod eviction request.
The rules specify that only CREATE
operations related to pods/eviction
sub-resources are intercepted.
If these rules are met, the API forwards the notification.
The clientConfig
points to the Strimzi Drain Cleaner service and /drainer
endpoint that exposes the webhook.
The webhook uses a secure TLS connection, which requires authentication.
The caBundle
property specifies the certificate chain to validate HTTPS communication.
Certificates are encoded in Base64.
Webhook configuration for pod eviction notifications
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
# ...
webhooks:
- name: strimzi-drain-cleaner.strimzi.io
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods/eviction"]
scope: "Namespaced"
clientConfig:
service:
namespace: "strimzi-drain-cleaner"
name: "strimzi-drain-cleaner"
path: /drainer
port: 443
caBundle: Cg==
# ...
To deploy and use the Strimzi Drain Cleaner, you need to download the deployment files.
Deploy the Strimzi Drain Cleaner to the Kubernetes cluster where the Cluster Operator and Kafka cluster are running.
Strimzi Drain Cleaner can run in two different modes.
By default, the Drain Cleaner denies (blocks) the Kubernetes eviction request to prevent Kubernetes from evicting the pods and instead uses the Cluster Operator to move the pod.
This mode has better compatibility with various cluster autoscaling tools and does not require any specific PodDisuptionBudget
configuration.
Alternatively, you can enable the legacy mode where it allows the eviction request while also instructing the Cluster Operator to move the pod.
For the legacy mode to work, you have to configure the PodDisruptionBudget
to not allow any pod evictions by setting the maxUnavailable
option to 0
.
Prerequisites
-
You have downloaded the Strimzi Drain Cleaner deployment files.
-
You have a highly available Kafka cluster deployment running with Kubernetes worker nodes that you would like to update.
-
Topics are replicated for high availability.
Topic configuration specifies a replication factor of at least 3 and a minimum number of in-sync replicas to 1 less than the replication factor.
Kafka topic replicated for high availability
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 1
replicas: 3
config:
# ...
min.insync.replicas: 2
# ...
Excluding Kafka or ZooKeeper
If you don’t want to include Kafka or ZooKeeper pods in Drain Cleaner operations, or if you prefer to use the Drain Cleaner in legacy mode, change the default environment variables in the Drain Cleaner Deployment
configuration file:
-
Set STRIMZI_DENY_EVICTION
to false
to use the legacy mode relying on the PodDisruptionBudget
configuration
-
Set STRIMZI_DRAIN_KAFKA
to false
to exclude Kafka pods
-
Set STRIMZI_DRAIN_ZOOKEEPER
to false
to exclude ZooKeeper pods
Example configuration to exclude ZooKeeper pods
apiVersion: apps/v1
kind: Deployment
spec:
# ...
template:
spec:
serviceAccountName: strimzi-drain-cleaner
containers:
- name: strimzi-drain-cleaner
# ...
env:
- name: STRIMZI_DENY_EVICTION
value: "true"
- name: STRIMZI_DRAIN_KAFKA
value: "true"
- name: STRIMZI_DRAIN_ZOOKEEPER
value: "false"
# ...
Procedure
-
If you are using the legacy mode activated by setting the STRIMZI_DENY_EVICTION
environment variable to false
, you must also configure the PodDisruptionBudget
resource.
Set maxUnavailable
to 0
(zero) in the Kafka and ZooKeeper sections of the Kafka
resource using template
settings.
Specifying a pod disruption budget
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
template:
podDisruptionBudget:
maxUnavailable: 0
# ...
zookeeper:
template:
podDisruptionBudget:
maxUnavailable: 0
# ...
This setting prevents the automatic eviction of pods in case of planned disruptions,
leaving the Strimzi Drain Cleaner and Cluster Operator to roll the pods on different worker nodes.
Add the same configuration for ZooKeeper if you want to use Strimzi Drain Cleaner to drain ZooKeeper nodes.
-
Update the Kafka
resource:
kubectl apply -f <kafka_configuration_file>
-
Deploy the Strimzi Drain Cleaner.
-
If you are using cert-manager
with Kubernetes, apply the resources in the /install/drain-cleaner/certmanager
directory.
kubectl apply -f ./install/drain-cleaner/certmanager
The TLS certificates for the webhook are generated automatically and injected into the webhook configuration.
-
If you are not using cert-manager
with Kubernetes, do the following:
-
Add TLS certificates to use in the deployment.
Any certificates you add must be renewed before they expire.
-
Apply the resources in the /install/drain-cleaner/kubernetes
directory.
kubectl apply -f ./install/drain-cleaner/kubernetes
Helm charts are used to package, configure, and deploy Kubernetes resources.
Strimzi provides a Helm chart to deploy the Strimzi Drain Cleaner.
The Drain Cleaner is deployed on the Kubernetes cluster with the default chart configuration, which assumes that cert-manager
issues the TLS certificates required by the Drain Cleaner.
You can install the Drain Cleaner with cert-manager
support or provide your own TLS certificates.
Default configuration values
Default configuration values are passed into the chart using parameters defined in a values.yaml
file.
If you don’t want to use the default configuration, you can override the defaults when you install the chart using the --set
argument.
You specify values in the format --set key=value[,key=value]
.
The values.yaml
file supplied with the Helm deployment files describes the available configuration parameters, including those shown in the following table.
Table 39. Chart configuration options
Parameter |
Description |
Default |
replicaCount
|
Number of replicas of the Drain Cleaner webhook |
1
|
image.registry
|
Drain Cleaner image registry |
quay.io
|
image.repository
|
Drain Cleaner image repository |
strimzi
|
image.name
|
Drain Cleaner image name |
drain-cleaner
|
image.tag
|
Drain Cleaner image tag |
latest
|
image.imagePullPolicy
|
Image pull policy for all pods deployed by the Drain Cleaner |
nil
|
secret.create
|
Set to true and add certificates when not using cert-manager |
false
|
namespace.name
|
Default namespace for the Drain Cleaner deployment. |
strimzi-drain-cleaner
|
resources
|
Configures resources for the Drain Cleaner pod |
[]
|
nodeSelector
|
Add a node selector to the Drain Cleaner pod |
{}
|
tolerations
|
Add tolerations to the Drain Cleaner pod |
[]
|
topologySpreadConstraints
|
Add topology spread constraints to the Drain Cleaner pod |
{}
|
affinity
|
Add affinities to the Drain Cleaner pod |
{}
|
Procedure
-
Deploy the Drain Cleaner:
helm install strimzi-drain-cleaner oci://quay.io/strimzi-helm/strimzi-drain-cleaner
Alternatively, you can use parameter values to install a specific version of the Drain Cleaner or specify any changes to the default configuration.
Example configuration that installs a specific version of the Drain Cleaner and changes the number of replicas
helm install strimzi-drain-cleaner --set replicaCount=2 --version 1.2.0 oci://quay.io/strimzi-helm/strimzi-drain-cleaner
-
Verify that the Drain Cleaner has been deployed successfully:
Use the Strimzi Drain Cleaner in combination with the Cluster Operator to move Kafka broker or ZooKeeper pods from nodes that are being drained.
When you run the Strimzi Drain Cleaner, it annotates pods with a rolling update pod annotation.
The Cluster Operator performs rolling updates based on the annotation.
Considerations when using anti-affinity configuration
When using anti-affinity with your Kafka or ZooKeeper pods, consider adding a spare worker node to your cluster.
Including spare nodes ensures that your cluster has the capacity to reschedule pods during node draining or temporary unavailability of other nodes.
When a worker node is drained, and anti-affinity rules restrict pod rescheduling on alternative nodes, spare nodes help prevent restarted pods from becoming unschedulable. This mitigates the risk of the draining operation failing.
Procedure
-
Drain a specified Kubernetes node hosting the Kafka broker or ZooKeeper pods.
kubectl get nodes
kubectl drain <name-of-node> --delete-emptydir-data --ignore-daemonsets --timeout=6000s --force
-
Check the eviction events in the Strimzi Drain Cleaner log to verify that the pods have been annotated for restart.
Strimzi Drain Cleaner log show annotations of pods
INFO ... Received eviction webhook for Pod my-cluster-zookeeper-2 in namespace my-project
INFO ... Pod my-cluster-zookeeper-2 in namespace my-project will be annotated for restart
INFO ... Pod my-cluster-zookeeper-2 in namespace my-project found and annotated for restart
INFO ... Received eviction webhook for Pod my-cluster-kafka-0 in namespace my-project
INFO ... Pod my-cluster-kafka-0 in namespace my-project will be annotated for restart
INFO ... Pod my-cluster-kafka-0 in namespace my-project found and annotated for restart
-
Check the reconciliation events in the Cluster Operator log to verify the rolling updates.
Cluster Operator log shows rolling updates
INFO PodOperator:68 - Reconciliation #13(timer) Kafka(my-project/my-cluster): Rolling Pod my-cluster-zookeeper-2
INFO PodOperator:68 - Reconciliation #13(timer) Kafka(my-project/my-cluster): Rolling Pod my-cluster-kafka-0
INFO AbstractOperator:500 - Reconciliation #13(timer) Kafka(my-project/my-cluster): reconciled
The Drain Cleaner uses a webhook to receive eviction notifications from the Kubernetes API.
The webhook uses a secure TLS connection and authenticates using TLS certificates.
If you are not deploying the Drain Cleaner using the cert-manager
or on Openshift, you must create and renew the TLS certificates.
You must then add them to the files used to deploy the Drain Cleaner.
The certificates must also be renewed before they expire.
To renew the certificates, you repeat the steps used to generate and add the certificates to the initial deployment of the Drain Cleaner.
Generate and add certificates to the standard installation files or your Helm configuration when deploying the Drain Cleaner on Kubernetes without cert-manager
.
Note
|
If you are using cert-manager to deploy the Drain Cleaner, you don’t need to add or renew TLS certificates. The same applies when deploying the Drain Cleaner on OpenShift, as OpenShift injects the certificates. In both cases, TLS certificates are added and renewed automatically.
|
Generating and renewing TLS certificates
-
From the command line, create a directory called tls-certificate
:
mkdir tls-certificate
cd tls-certificate
Now use OpenSSL to create the certificates in the tls-certificate
directory.
-
Generate a CA (Certificate Authority) public certificate and private key:
openssl req -nodes -new -x509 -keyout ca.key -out ca.crt -subj "/CN=Strimzi Drain Cleaner CA"
A ca.crt
and ca.key
file are created.
-
Generate a private key for the Drain Cleaner:
openssl genrsa -out tls.key 2048
A tls.key
file is created.
-
Generate a CSR (Certificate Signing Request) and sign it by adding the CA public certificate (ca.crt
) you generated:
openssl req -new -key tls.key -subj "/CN=strimzi-drain-cleaner.strimzi-drain-cleaner.svc" \
| openssl x509 -req -CA ca.crt -CAkey ca.key -CAcreateserial -extfile <(printf "subjectAltName=DNS:strimzi-drain-cleaner.strimzi-drain-cleaner.svc") -out tls.crt
A tls.crt
file is created.
Note
|
If you change the name of the Strimzi Drain Cleaner service or install it into a different namespace, you must change the SAN (Subject Alternative Name) of the certificate, following the format <service_name>.<namespace>.svc .
|
-
Encode the CA public certificate into base64.
base64 tls-certificate/ca.crt
With the certificates generated, add them to the installation files or to your Helm configuration depending on your deployment method.
Adding the TLS certificates to the Drain Cleaner installation files
-
Copy the base64-encoded CA public certificate as the value for the caBundle
property of the 070-ValidatingWebhookConfiguration.yaml
installation file:
# ...
clientConfig:
service:
namespace: "strimzi-drain-cleaner"
name: "strimzi-drain-cleaner"
path: /drainer
port: 443
caBundle: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0...
# ...
-
Create a namespace called strimzi-drain-cleaner
in your Kubernetes cluster:
kubectl create ns strimzi-drain-cleaner
-
Create a secret named strimzi-drain-cleaner
with the tls.crt
and tls.key
files you generated:
kubectl create secret tls strimzi-drain-cleaner \
-n strimzi-drain-cleaner \
--cert=tls-certificate/tls.crt \
--key=tls-certificate/tls.key
The secret is used in the Drain Cleaner deployment.
Example secret for the Drain Cleaner deployment
apiVersion: v1
kind: Secret
metadata:
# ...
name: strimzi-drain-cleaner
namespace: strimzi-drain-cleaner
# ...
data:
tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS...
tls.key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLR...
Adding the TLS certificates to a Helm deployment
-
Edit the values.yaml
configuration file used in the Helm deployment.
-
Set the certManager.create
parameter to false
.
-
Set the secret.create
parameter to true
.
-
Copy the certificates as secret
parameters.
Example secret configuration for the Drain Cleaner deployment
# ...
certManager:
create: false
secret:
create: true
tls_crt: "Cg==" # (1)
tls_key: "Cg==" # (2)
ca_bundle: "Cg==" # (3)
-
The public key (tls.crt
) signed by the CA public certificate.
-
The private key (tls.key
).
-
The base-64 encoded CA public certificate (ca.crt
).
By default, the Drain Cleaner deployment watches the secret containing the TLS certificates its uses for authentication.
The Drain Cleaner watches for changes, such as certificate renewals.
If it detects a change, it restarts to reload the TLS certificates.
The Drain Cleaner installation files enable this behavior by default.
But you can disable the watching of certificates by setting the STRIMZI_CERTIFICATE_WATCH_ENABLED
environment variable to false
in the Deployment
configuration (060-Deployment.yaml
) of the Drain Cleaner installation files.
With STRIMZI_CERTIFICATE_WATCH_ENABLED
enabled, you can also use the following environment variables for watching TLS certificates.
Table 40. Drain Cleaner environment variables for watching TLS certificates
Environment Variable |
Description |
Default |
STRIMZI_CERTIFICATE_WATCH_ENABLED
|
Enables or disables the certificate watch |
false
|
STRIMZI_CERTIFICATE_WATCH_NAMESPACE
|
The namespace where the Drain Cleaner is deployed and where the certificate secret exists |
strimzi-drain-cleaner
|
STRIMZI_CERTIFICATE_WATCH_POD_NAME
|
The Drain Cleaner pod name |
- |
STRIMZI_CERTIFICATE_WATCH_SECRET_NAME
|
The name of the secret containing TLS certificates |
strimzi-drain-cleaner
|
STRIMZI_CERTIFICATE_WATCH_SECRET_KEYS
|
The list of fields inside the secret that contain the TLS certificates |
tls.crt, tls.key
|
Example environment variable configuration to control watch operations
apiVersion: apps/v1
kind: Deployment
metadata:
name: strimzi-drain-cleaner
labels:
app: strimzi-drain-cleaner
namespace: strimzi-drain-cleaner
spec:
# ...
spec:
serviceAccountName: strimzi-drain-cleaner
containers:
- name: strimzi-drain-cleaner
# ...
env:
- name: STRIMZI_DRAIN_KAFKA
value: "true"
- name: STRIMZI_DRAIN_ZOOKEEPER
value: "true"
- name: STRIMZI_CERTIFICATE_WATCH_ENABLED
value: "true"
- name: STRIMZI_CERTIFICATE_WATCH_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STRIMZI_CERTIFICATE_WATCH_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
# ...
Tip
|
Use the Downward API mechanism to configure STRIMZI_CERTIFICATE_WATCH_NAMESPACE and STRIMZI_CERTIFICATE_WATCH_POD_NAME .
|
Use annotations to manually trigger a rolling update of Kafka and other operands through the Cluster Operator.
Initiate rolling updates of Kafka, Kafka Connect, MirrorMaker 2, and ZooKeeper clusters.
Manually performing a rolling update on a specific pod or set of pods is usually only required in exceptional circumstances.
However, rather than deleting the pods directly, if you perform the rolling update through the Cluster Operator you ensure the following:
-
The manual deletion of the pod does not conflict with simultaneous Cluster Operator operations, such as deleting other pods in parallel.
-
The Cluster Operator logic handles the Kafka configuration specifications, such as the number of in-sync replicas.
This procedure describes how to trigger a rolling update of Kafka, Kafka Connect, MirrorMaker 2, or ZooKeeper clusters.
To trigger the update, you add an annotation to the StrimziPodSet
that manages the pods running on the cluster.
Prerequisites
To perform a manual rolling update, you need a running Cluster Operator.
The cluster for the component you are updating, whether it’s Kafka, Kafka Connect, MirrorMaker 2, or ZooKeeper, must also be running.
Procedure
-
Find the name of the resource that controls the pods you want to manually update.
For example, if your Kafka cluster is named my-cluster, the corresponding names are my-cluster-kafka and my-cluster-zookeeper.
For a Kafka Connect cluster named my-connect-cluster, the corresponding name is my-connect-cluster-connect.
And for a MirrorMaker 2 cluster named my-mm2-cluster, the corresponding name is my-mm2-cluster-mirrormaker2.
-
Use kubectl annotate
to annotate the appropriate resource in Kubernetes.
Annotating a StrimziPodSet
kubectl annotate strimzipodset <cluster_name>-kafka strimzi.io/manual-rolling-update="true"
kubectl annotate strimzipodset <cluster_name>-zookeeper strimzi.io/manual-rolling-update="true"
kubectl annotate strimzipodset <cluster_name>-connect strimzi.io/manual-rolling-update="true"
kubectl annotate strimzipodset <cluster_name>-mirrormaker2 strimzi.io/manual-rolling-update="true"
-
Wait for the next reconciliation to occur (every two minutes by default).
A rolling update of all pods within the annotated resource is triggered, as long as the annotation was detected by the reconciliation process.
When the rolling update of all the pods is complete, the annotation is automatically removed from the resource.
This procedure describes how to manually trigger a rolling update of existing Kafka, Kafka Connect, MirrorMaker 2, or ZooKeeper clusters using a Kubernetes Pod
annotation.
When multiple pods are annotated, consecutive rolling updates are performed within the same reconciliation run.
Prerequisites
To perform a manual rolling update, you need a running Cluster Operator.
The cluster for the component you are updating, whether it’s Kafka, Kafka Connect, MirrorMaker 2, or ZooKeeper, must also be running.
You can perform a rolling update on a Kafka cluster regardless of the topic replication factor used.
But for Kafka to stay operational during the update, you’ll need the following:
Procedure
-
Find the name of the Pod
you want to manually update.
Pod naming conventions are as follows:
-
<cluster_name>-kafka-<index_number>
for a Kafka cluster
-
<cluster_name>-zookeeper-<index_number>
for a ZooKeeper cluster
-
<cluster_name>-connect-<index_number>
for a Kafka Connect cluster
-
<cluster_name>-mirrormaker2-<index_number>
for a MirrorMaker 2 cluster
The <index_number>
assigned to a pod starts at zero and ends at the total number of replicas minus one.
-
Use kubectl annotate
to annotate the Pod
resource in Kubernetes:
kubectl annotate pod <cluster_name>-kafka-<index_number> strimzi.io/manual-rolling-update="true"
kubectl annotate pod <cluster_name>-zookeeper-<index_number> strimzi.io/manual-rolling-update="true"
kubectl annotate pod <cluster_name>-connect-<index_number> strimzi.io/manual-rolling-update="true"
kubectl annotate pod <cluster_name>-mirrormaker2-<index_number> strimzi.io/manual-rolling-update="true"
-
Wait for the next reconciliation to occur (every two minutes by default).
A rolling update of the annotated Pod
is triggered, as long as the annotation was detected by the reconciliation process.
When the rolling update of a pod is complete, the annotation is automatically removed from the Pod
.
Note
|
If the ContinueReconciliationOnManualRollingUpdateFailure feature gate is enabled, reconciliation continues even if the manual rolling update of the cluster fails.
This allows the Cluster Operator to recover from certain rectifiable situations that can be addressed later in the reconciliation.
For example, it can recreate a missing Persistent Volume Claim (PVC) or Persistent Volume (PV) that caused the update to fail.
|
After the Cluster Operator restarts a Kafka pod in a Kubernetes cluster, it emits a Kubernetes event into the pod’s namespace explaining why the pod restarted.
For help in understanding cluster behavior, you can check restart events from the command line.
Tip
|
You can export and monitor restart events using metrics collection tools like Prometheus. Use the metrics tool with an event exporter that can export the output in a suitable format.
|
The Cluster Operator initiates a restart event for a specific reason.
You can check the reason by fetching information on the restart event.
Table 41. Restart reasons
Event |
Description |
|
The pod is still using a server certificate signed with an old CA, so needs to be restarted as part of the certificate update. |
|
Expired CA certificates have been removed, and the pod is restarted to run with the current certificates. |
|
CA certificates have been renewed, and the pod is restarted to run with the updated certificates. |
|
The key used to sign clients CA certificates has been replaced, and the pod is being restarted as part of the CA renewal process. |
|
The key used to sign the cluster’s CA certificates has been replaced, and the pod is being restarted as part of the CA renewal process. |
ConfigChangeRequiresRestart
|
Some Kafka configuration properties are changed dynamically, but others require that the broker be restarted. |
|
The file system size has been increased, and a restart is needed to apply it. |
|
One or more TLS certificates used by the Kafka broker have been updated, and a restart is needed to use them. |
|
A user annotated the pod, or the StrimziPodSet set it belongs to, to trigger a restart. |
|
An error occurred that requires a pod restart to rectify. |
|
A disk was added or removed from the Kafka volumes, and a restart is needed to apply the change. When using StrimziPodSet resources, the same reason is given if the pod needs to be recreated. |
|
The StrimziPodSet that the pod is a member of has been updated, so the pod needs to be recreated. When using StrimziPodSet resources, the same reason is given if a disk was added or removed from the Kafka volumes. |
|
The pod is still pending, and is not scheduled or cannot be scheduled, so the operator has restarted the pod in a final attempt to get it running. |
|
Strimzi was unable to connect to the pod, which can indicate a broker not starting correctly, so the operator restarted it in an attempt to resolve the issue. |
When checking restart events from the command line, you can specify a field-selector
to filter on Kubernetes event fields.
The following fields are available when filtering events with field-selector
.
regardingObject.kind
-
The object that was restarted, and for restart events, the kind is always Pod
.
regarding.namespace
-
The namespace that the pod belongs to.
regardingObject.name
-
The pod’s name, for example, strimzi-cluster-kafka-0
.
regardingObject.uid
-
The unique ID of the pod.
reason
-
The reason the pod was restarted, for example, JbodVolumesChanged
.
reportingController
-
The reporting component is always strimzi.io/cluster-operator
for Strimzi restart events.
source
-
source
is an older version of reportingController
. The reporting component is always strimzi.io/cluster-operator
for Strimzi restart events.
type
-
The event type, which is either Warning
or Normal
. For Strimzi restart events, the type is Normal
.
Note
|
In older versions of Kubernetes, the fields using the regarding prefix might use an involvedObject prefix instead. reportingController was previously called reportingComponent .
|
Use a kubectl
command to list restart events initiated by the Cluster Operator.
Filter restart events emitted by the Cluster Operator by setting the Cluster Operator as the reporting component using the reportingController
or source
event fields.
Procedure
-
Get all restart events emitted by the Cluster Operator:
kubectl -n kafka get events --field-selector reportingController=strimzi.io/cluster-operator
Example showing events returned
LAST SEEN TYPE REASON OBJECT MESSAGE
2m Normal CaCertRenewed pod/strimzi-cluster-kafka-0 CA certificate renewed
58m Normal PodForceRestartOnError pod/strimzi-cluster-kafka-1 Pod needs to be forcibly restarted due to an error
5m47s Normal ManualRollingUpdate pod/strimzi-cluster-kafka-2 Pod was manually annotated to be rolled
You can also specify a reason
or other field-selector
options to constrain the events returned.
Here, a specific reason is added:
kubectl -n kafka get events --field-selector reportingController=strimzi.io/cluster-operator,reason=PodForceRestartOnError
-
Use an output format, such as YAML, to return more detailed information about one or more events.
kubectl -n kafka get events --field-selector reportingController=strimzi.io/cluster-operator,reason=PodForceRestartOnError -o yaml
Example showing detailed events output
apiVersion: v1
items:
- action: StrimziInitiatedPodRestart
apiVersion: v1
eventTime: "2022-05-13T00:22:34.168086Z"
firstTimestamp: null
involvedObject:
kind: Pod
name: strimzi-cluster-kafka-1
namespace: kafka
kind: Event
lastTimestamp: null
message: Pod needs to be forcibly restarted due to an error
metadata:
creationTimestamp: "2022-05-13T00:22:34Z"
generateName: strimzi-event
name: strimzi-eventwppk6
namespace: kafka
resourceVersion: "432961"
uid: 29fcdb9e-f2cf-4c95-a165-a5efcd48edfc
reason: PodForceRestartOnError
reportingController: strimzi.io/cluster-operator
reportingInstance: strimzi-cluster-operator-6458cfb4c6-6bpdp
source: {}
type: Normal
kind: List
metadata:
resourceVersion: ""
selfLink: ""
The following fields are deprecated, so they are not populated for these events:
-
firstTimestamp
-
lastTimestamp
-
source
Upgrade your Strimzi installation to version 0.43.0 and benefit from new features, performance improvements, and enhanced security options.
During the upgrade, Kafka is also be updated to the latest supported version, introducing additional features and bug fixes to your Strimzi deployment.
Use the same method to upgrade the Cluster Operator as the initial method of deployment.
For example, if you used the Strimzi installation files, modify those files to perform the upgrade.
After you have upgraded your Cluster Operator to 0.43.0, the next step is to upgrade all Kafka nodes to the latest supported version of Kafka.
Kafka upgrades are performed by the Cluster Operator through rolling updates of the Kafka nodes.
If you encounter any issues with the new version, Strimzi can be downgraded to the previous version.
Upgrade without downtime
For topics configured with high availability (replication factor of at least 3 and evenly distributed partitions), the upgrade process should not cause any downtime for consumers and producers.
The upgrade triggers rolling updates, where brokers are restarted one by one at different stages of the process.
During this time, overall cluster availability is temporarily reduced, which may increase the risk of message loss in the event of a broker failure.
To upgrade brokers and clients without downtime, you must complete the Strimzi upgrade procedures in the following order:
-
Make sure your Kubernetes cluster version is supported.
Strimzi 0.43.0 requires Kubernetes 1.23 and later.
-
Upgrade the Cluster Operator.
-
Upgrade Kafka depending on the cluster configuration:
Note
|
From Strimzi 0.39, upgrades and downgrades between KRaft-based clusters are supported.
|
Two upgrade paths are available for Strimzi.
- Incremental upgrade
-
An incremental upgrade involves upgrading Strimzi from the previous minor version to version 0.43.0.
- Multi-version upgrade
-
A multi-version upgrade involves upgrading an older version of Strimzi to version 0.43.0 within a single upgrade, skipping one or more intermediate versions.
For example, upgrading directly from Strimzi 0.30.0 to Strimzi 0.43.0 is possible.
When upgrading Strimzi, it is important to ensure compatibility with the Kafka version being used.
Multi-version upgrades are possible even if the supported Kafka versions differ between the old and new versions.
However, if you attempt to upgrade to a new Strimzi version that does not support the current Kafka version, an error indicating that the Kafka version is not supported is generated.
In this case, you must upgrade the Kafka version as part of the Strimzi upgrade by changing the spec.kafka.version
in the Kafka
custom resource to the supported version for the new Strimzi version.
Note
|
-
The Operators column lists all released Strimzi versions (the Strimzi version is often called the "Operator version").
-
The Kafka versions column lists the supported Kafka versions for each Strimzi version.
|
If you are upgrading to the latest version of Strimzi from a version prior to version 0.22, do the following:
-
Upgrade Strimzi to version 0.22 following the standard sequence.
-
Convert Strimzi custom resources to v1beta2
using the API conversion tool provided with Strimzi.
-
Do one of the following:
-
Upgrade Strimzi to a version between 0.23 and 0.26 (where the ControlPlaneListener
feature gate is disabled by default).
-
Upgrade Strimzi to a version between 0.27 and 0.31 (where the ControlPlaneListener
feature gate is enabled by default) with the ControlPlaneListener
feature gate disabled.
-
Enable the ControlPlaneListener
feature gate.
-
Upgrade to Strimzi 0.43.0 following the standard sequence.
Strimzi custom resources started using the v1beta2
API version in release 0.22.
CRDs and custom resources must be converted before upgrading to Strimzi 0.23 or newer.
For information on using the API conversion tool, see the Strimzi 0.24.0 upgrade documentation.
Note
|
As an alternative to first upgrading to version 0.22, you can install the custom resources from version 0.22 and then convert the resources.
|
The ControlPlaneListener
feature is now permanently enabled in Strimzi.
You must upgrade to a version of Strimzi where it is disabled, then enable it using the
STRIMZI_FEATURE_GATES
environment variable in the Cluster Operator configuration.
Disabling the ControlPlaneListener
feature gate
env:
- name: STRIMZI_FEATURE_GATES
value: -ControlPlaneListener
Enabling the ControlPlaneListener
feature gate
env:
- name: STRIMZI_FEATURE_GATES
value: +ControlPlaneListener
When upgrading Kafka, consider your settings for the STRIMZI_KAFKA_IMAGES
environment variable and the Kafka.spec.kafka.version
property.
-
Each Kafka
resource can be configured with a Kafka.spec.kafka.version
, which defaults to the latest supported Kafka version (3.8.0) if not specified.
-
The Cluster Operator’s STRIMZI_KAFKA_IMAGES
environment variable provides a mapping (<kafka_version>=<image>) between a Kafka version and the image to be used when a specific Kafka version is requested in a given Kafka
resource. For example, 3.8.0=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0.
-
If Kafka.spec.kafka.image
is not configured, the default image for the given version is used.
-
If Kafka.spec.kafka.image
is configured, the default image is overridden.
Warning
|
The Cluster Operator cannot validate that an image actually contains a Kafka broker of the expected version.
Take care to ensure that the given image corresponds to the given Kafka version.
|
Upgrading Kafka clients ensures that they benefit from the features, fixes, and improvements that are introduced in new versions of Kafka.
Upgraded clients maintain compatibility with other upgraded Kafka components.
The performance and stability of the clients might also be improved.
Consider the best approach for upgrading Kafka clients and brokers to ensure a smooth transition.
The chosen upgrade strategy depends on whether you are upgrading brokers or clients first.
Since Kafka 3.0, you can upgrade brokers and client independently and in any order.
The decision to upgrade clients or brokers first depends on several factors, such as the number of applications that need to be upgraded and how much downtime is tolerable.
If you upgrade clients before brokers, some new features may not work as they are not yet supported by brokers.
However, brokers can handle producers and consumers running with different versions and supporting different log message versions.
When performing your upgrade, ensure the availability of your Kafka clusters by following these steps:
-
Configure pod disruption budgets
-
Roll pods using one of these methods:
-
Use the Strimzi Drain Cleaner (recommended)
-
Apply an annotation to your pods to roll them manually
For Kafka to stay operational, topics must also be replicated for high availability.
This requires topic configuration that specifies a replication factor of at least 3 and a minimum number of in-sync replicas to 1 less than the replication factor.
Kafka topic replicated for high availability
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
name: my-topic
labels:
strimzi.io/cluster: my-cluster
spec:
partitions: 1
replicas: 3
config:
# ...
min.insync.replicas: 2
# ...
In a highly available environment, the Cluster Operator maintains a minimum number of in-sync replicas for topics during the upgrade process so that there is no downtime.
When using the Strimzi Drain Cleaner to evict nodes during Kubernetes upgrade, it annotates pods with a manual rolling update annotation to inform the Cluster Operator to perform a rolling update of the pod that should be evicted and have it moved away from the Kubernetes node that is being upgraded.
As an alternative to using the Drain Cleaner to roll pods, you can trigger a manual rolling update of pods through the Cluster Operator.
Using Pod
resources, rolling updates restart the pods of resources with new pods.
To replicate the operation of the Drain Cleaner by keeping topics available, you must also set the maxUnavailable
value to zero for the pod disruption budget.
Reducing the pod disruption budget to zero prevents Kubernetes from evicting pods automatically.
Specifying a pod disruption budget
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
namespace: myproject
spec:
kafka:
# ...
template:
podDisruptionBudget:
maxUnavailable: 0
# ...
You need to watch the pods that need to be drained.
You then add a pod annotation to make the update.
Here, the annotation updates a Kafka pod named my-cluster-pool-a-1
.
Performing a manual rolling update on a Kafka pod
kubectl annotate pod my-cluster-pool-a-1 strimzi.io/manual-rolling-update="true"
Use the same method to upgrade the Cluster Operator as the initial method of deployment.
This procedure describes how to upgrade a Cluster Operator deployment to use Strimzi 0.43.0.
Follow this procedure if you deployed the Cluster Operator using the installation YAML files in the install/cluster-operator/
directory.
The steps include the necessary configuration changes when the Cluster Operator watches multiple or all namespaces.
The availability of Kafka clusters managed by the Cluster Operator is not affected by the upgrade operation.
Note
|
Refer to the documentation supporting a specific version of Strimzi for information on how to upgrade to that version.
|
Procedure
-
Take note of any configuration changes made during the previous Cluster Operator installation.
Any changes will be overwritten by the new version of the Cluster Operator.
-
Update your custom resources to reflect the supported configuration options available for Strimzi version 0.43.0.
-
Modify the installation files for the new Cluster Operator version to reflect the namespace in which the Cluster Operator is running.
sed -i 's/namespace: .*/namespace: my-cluster-operator-namespace/' install/cluster-operator/*RoleBinding*.yaml
sed -i '' 's/namespace: .*/namespace: my-cluster-operator-namespace/' install/cluster-operator/*RoleBinding*.yaml
-
If you modified environment variables in the Deployment
configuration, edit the
060-Deployment-strimzi-cluster-operator.yaml
file to use those environment variables.
-
If the Cluster Operator is watching multiple namespaces, add the list of namespaces to the STRIMZI_NAMESPACE
environment variable.
-
If the Cluster Operator is watching all namespaces, specify value: "*"
for the STRIMZI_NAMESPACE
environment variable.
-
If the Cluster Operator is watching more than one namespace, update the role bindings.
-
If watching multiple namespaces, replace the namespace
in the RoleBinding
installation files with the actual namespace name and create the role bindings for each namespace:
Creating role bindings for a namespace
kubectl create -f install/cluster-operator/020-RoleBinding-strimzi-cluster-operator.yaml -n <watched_namespace>
kubectl create -f install/cluster-operator/023-RoleBinding-strimzi-cluster-operator.yaml -n <watched_namespace>
kubectl create -f install/cluster-operator/031-RoleBinding-strimzi-cluster-operator-entity-operator-delegation.yaml -n <watched_namespace>
For example, if the Cluster Operator is watching three namespaces, create three sets of role bindings by substituting <watched_namespace>
with the name of each namespace.
-
If watching all namespaces, recreate the cluster role bindings that grant cluster-wide access (if needed):
Granting cluster-wide access using role bindings
kubectl create clusterrolebinding strimzi-cluster-operator-namespaced --clusterrole=strimzi-cluster-operator-namespaced --serviceaccount my-cluster-operator-namespace:strimzi-cluster-operator
kubectl create clusterrolebinding strimzi-cluster-operator-watched --clusterrole=strimzi-cluster-operator-watched --serviceaccount my-cluster-operator-namespace:strimzi-cluster-operator
kubectl create clusterrolebinding strimzi-cluster-operator-entity-operator-delegation --clusterrole=strimzi-entity-operator --serviceaccount my-cluster-operator-namespace:strimzi-cluster-operator
-
When you have an updated configuration, deploy it along with the rest of the installation resources:
kubectl replace -f install/cluster-operator
Wait for the rolling updates to complete.
-
If the new operator version no longer supports the Kafka version you are upgrading from, an error message is returned.
To resolve this, upgrade to a supported Kafka version:
-
Edit the Kafka
custom resource.
-
Change the spec.kafka.version
property to a supported Kafka version.
If no error message is returned, you can proceed to the next step and upgrade the Kafka version later.
-
Get the image for the Kafka pod to ensure the upgrade was successful:
kubectl get pods my-cluster-kafka-0 -o jsonpath='{.spec.containers[0].image}'
The image tag shows the new Strimzi version followed by the Kafka version:
quay.io/strimzi/kafka:0.43.0-kafka-3.8.0
The Cluster Operator is upgraded to version 0.43.0, but the version of Kafka running in the cluster it manages is unchanged.
If you deployed Strimzi from OperatorHub.io, use the Operator Lifecycle Manager (OLM) to change the update channel for the Strimzi operators to a new Strimzi version.
Updating the channel starts one of the following types of upgrade, depending on your chosen upgrade strategy:
Note
|
If you subscribe to the stable channel, you can get automatic updates without changing channels.
However, enabling automatic updates is not recommended because of the potential for missing any pre-installation upgrade steps.
Use automatic upgrades only on version-specific channels.
|
If you deployed the Cluster Operator using a Helm chart, use helm upgrade
.
If you upgrade the Cluster Operator to a version that does not support the current version of Kafka you are using, you get an unsupported Kafka version error.
This error applies to all installation methods and means that you must upgrade Kafka to a supported Kafka version.
Change the spec.kafka.version
in the Kafka
resource to the supported version.
You can use kubectl
to check for error messages like this in the status
of the Kafka
resource.
Checking the Kafka status for errors
kubectl get kafka <kafka_cluster_name> -n <namespace> -o jsonpath='{.status.conditions}'
Replace <kafka_cluster_name> with the name of your Kafka cluster and <namespace> with the Kubernetes namespace where the pod is running.
When deploying the Topic Operator to manage topics, the Cluster Operator enables unidirectional topic management.
This means that the Topic Operator only manages Kafka topics associated with KafkaTopic
resources and does not interfere with topics managed independently within the Kafka cluster.
Previously, the Topic Operator worked in bidirectional mode, which meant it could also perform operations on topics within the Kafka cluster.
If you are switching from a version of Strimzi that uses the Bidirectional Topic Operator, after upgrading the Cluster Operator, perform some cleanup tasks on the following internal topics that were used by the operator:
-
strimzi-store-topic
-
strimzi-topic-operator
-
consumer-offsets
-
transaction-state
For the strimzi-store-topic
and strimzi-topic-operator
topics, delete the resources that were used to manage them:
Deleting internal topics used by the operator
kubectl delete $(kubectl get kt -n <namespace> -o name | grep strimzi-store-topic) -n <namespace> \
&& kubectl delete $(kubectl get kt -n <namespace> -o name | grep strimzi-topic-operator) -n <namespace>
For the internal topics for storing consumer offsets and transaction states, consumer-offsets
and transaction-state
, you want to retain them in Kafka, but you don’t want them to be managed by the Topic Operator.
Discontinue their management before deleting their resources.
Annotating the KafkaTopic
resources with strimzi.io/managed="false"
indicates that the Topic Operator should no longer manage those topics:
Discontinuing management of internal topics
kubectl annotate $(kubectl get kt -n <namespace> -o name | grep consumer-offsets) strimzi.io/managed="false" -n <namespace> \
&& kubectl annotate $(kubectl get kt -n <namespace> -o name | grep transaction-state) strimzi.io/managed="false" -n <namespace>
Check the statuses of the KafkaTopic
resources to make sure the reconciliation was successful and the topics are no longer managed, as shown in the procedure to stop managing topics.
Having discontinued their management, delete the KafkaTopic
resources:
Deleting the resources for managing internal topics
kubectl delete $(kubectl get kt -n <namespace> -o name | grep consumer-offsets) -n <namespace> \
&& kubectl delete $(kubectl get kt -n <namespace> -o name | grep transaction-state) -n <namespace>
By discontinuing their management, they won’t also be deleted in Kafka.
Upgrade a KRaft-based Kafka cluster to a newer supported Kafka version and KRaft metadata version.
Note
|
Refer to the Apache Kafka documentation for the latest on support for KRaft-based upgrades.
|
Prerequisites
-
The Cluster Operator is up and running.
-
Before you upgrade the Kafka cluster, check that the properties of the Kafka
resource do not contain configuration options that are not supported in the new Kafka version.
Procedure
-
Update the Kafka cluster configuration:
kubectl edit kafka <kafka_configuration_file>
-
If configured, check that the current spec.kafka.metadataVersion
is set to a version supported by the version of Kafka you are upgrading to.
For example, the current version is 3.7-IV4 if upgrading from Kafka version 3.7.0 to 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
metadataVersion: 3.7-IV4
version: 3.7.0
# ...
If metadataVersion
is not configured,
Strimzi automatically updates it to the current default after the update to the Kafka version in the next step.
Note
|
The value of metadataVersion must be a string to prevent it from being interpreted as a floating point number.
|
-
Change the Kafka.spec.kafka.version
to specify the new Kafka version; leave the metadataVersion
at the default for the current Kafka version.
Note
|
Changing the kafka.version ensures that all brokers in the cluster are upgraded to start using the new broker binaries.
During this process, some brokers are using the old binaries while others have already upgraded to the new ones.
Leaving the metadataVersion unchanged at the current setting ensures that the Kafka brokers and controllers can continue to communicate with each other throughout the upgrade.
|
For example, if upgrading from Kafka 3.7.0 to 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
metadataVersion: 3.7-IV4 # (1)
version: 3.8.0 # (2)
# ...
-
Metadata version is unchanged
-
Kafka version is changed to the new version.
-
If the image for the Kafka cluster is defined in Kafka.spec.kafka.image
of the Kafka
custom resource, update the image
to point to a container image with the new Kafka version.
-
Save and exit the editor, then wait for the rolling updates to upgrade the Kafka nodes to complete.
Check the progress of the rolling updates by watching the pod state transitions:
kubectl get pods my-cluster-kafka-0 -o jsonpath='{.spec.containers[0].image}'
The rolling updates ensure that each pod is using the broker binaries for the new version of Kafka.
-
If required, set the version
property for Kafka Connect and MirrorMaker as the new version of Kafka:
-
For Kafka Connect, update KafkaConnect.spec.version
.
-
For MirrorMaker, update KafkaMirrorMaker.spec.version
.
-
For MirrorMaker 2, update KafkaMirrorMaker2.spec.version
.
Note
|
If you are using custom images that are built manually, you must rebuild those images to ensure that they are up-to-date with the latest Strimzi base image.
For example, if you created a container image from the base Kafka Connect image, update the Dockerfile to point to the latest base image and build configuration.
|
-
If configured, update the Kafka resource to use the new metadataVersion
version. Otherwise, go to step 9.
For example, if upgrading to Kafka 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
metadataVersion: 3.8-IV0
version: 3.8.0
# ...
Warning
|
Exercise caution when changing the metadataVersion , as downgrading may not be possible.
You cannot downgrade Kafka if the metadataVersion for the new Kafka version is higher than the Kafka version you wish to downgrade to.
However, understand the potential implications on support and compatibility when maintaining an older version.
|
-
Wait for the Cluster Operator to update the cluster.
Upgrading client applications
Ensure all Kafka client applications are updated to use the new version of the client binaries as part of the upgrade process and verify their compatibility with the Kafka upgrade.
If needed, coordinate with the team responsible for managing the client applications.
Tip
|
To check that a client is using the latest message format, use the kafka.server:type=BrokerTopicMetrics,name={Produce|Fetch}MessageConversionsPerSec metric.
The metric shows 0 if the latest message format is being used.
|
If you are using a ZooKeeper-based Kafka cluster, an upgrade requires an update to the Kafka version and the inter-broker protocol version.
If you want to switch a Kafka cluster from using ZooKeeper for metadata management to operating in KRaft mode, the steps must be performed separately from the upgrade.
For information on migrating to a KRaft-based cluster, see Migrating to KRaft mode.
Upgrading Kafka when using ZooKeeper for cluster management requires updates to the Kafka version (Kafka.spec.kafka.version
) and its inter-broker protocol version (inter.broker.protocol.version
) in the configuration of the Kafka
resource.
Each version of Kafka has a compatible version of the inter-broker protocol.
The inter-broker protocol is used for inter-broker communication.
The minor version of the protocol typically increases to match the minor version of Kafka, as shown in the preceding table.
The inter-broker protocol version is set cluster wide in the Kafka
resource.
To change it, you edit the inter.broker.protocol.version
property in Kafka.spec.kafka.config
.
The following table shows the differences between Kafka versions:
Table 42. Kafka version differences
Kafka version |
Inter-broker protocol version |
Log message format version |
ZooKeeper version |
3.7.0 |
3.7 |
3.7 |
3.8.3 |
3.7.1 |
3.7 |
3.7 |
3.8.4 |
3.8.0 |
3.8 |
3.8 |
3.8.4 |
Log message format version
When a producer sends a message to a Kafka broker, the message is encoded using a specific format.
The format can change between Kafka releases, so messages specify which version of the message format they were encoded with.
The properties used to set a specific message format version are as follows:
From Kafka 3.0.0, the message format version values are assumed to match the inter.broker.protocol.version
and don’t need to be set.
The values reflect the Kafka version used.
When upgrading to Kafka 3.0.0 or higher, you can remove these settings when you update the inter.broker.protocol.version
.
Otherwise, you can set the message format version based on the Kafka version you are upgrading to.
The default value of message.format.version
for a topic is defined by the log.message.format.version
that is set on the Kafka broker.
You can manually set the message.format.version
of a topic by modifying its topic configuration.
Rolling updates from Kafka version changes
The Cluster Operator initiates rolling updates to Kafka brokers when the Kafka version is updated.
Further rolling updates depend on the configuration for inter.broker.protocol.version
and log.message.format.version
.
If Kafka.spec.kafka.config contains… |
The Cluster Operator initiates… |
Both the inter.broker.protocol.version and the log.message.format.version . |
A single rolling update. After the update, the inter.broker.protocol.version must be updated manually, followed by log.message.format.version .
Changing each will trigger a further rolling update. |
Either the inter.broker.protocol.version or the log.message.format.version . |
Two rolling updates. |
No configuration for the inter.broker.protocol.version or the log.message.format.version . |
Two rolling updates. |
Important
|
From Kafka 3.0.0, when the inter.broker.protocol.version is set to 3.0 or higher, the log.message.format.version option is ignored and doesn’t need to be set.
The log.message.format.version property for brokers and the message.format.version property for topics are deprecated and will be removed in a future release of Kafka.
|
As part of the Kafka upgrade, the Cluster Operator initiates rolling updates for ZooKeeper.
Before Kafka 3.0, you could configure a specific message format for brokers using the log.message.format.version
property (or the message.format.version
property at the topic level).
This allowed brokers to accommodate older Kafka clients that were using an outdated message format.
Though Kafka inherently supports older clients without explicitly setting this property, brokers would then need to convert the messages from the older clients, which came with a significant performance cost.
Apache Kafka Java clients have supported the latest message format version since version 0.11.
If all of your clients are using the latest message version, you can remove the log.message.format.version
or message.format.version
overrides when upgrading your brokers.
However, if you still have clients that are using an older message format version, we recommend upgrading your clients first.
Start with the consumers, then upgrade the producers before removing the log.message.format.version
or message.format.version
overrides when upgrading your brokers.
This will ensure that all of your clients can support the latest message format version and that the upgrade process goes smoothly.
You can track Kafka client names and versions using this metric:
-
kafka.server:type=socket-server-metrics,clientSoftwareName=<name>,clientSoftwareVersion=<version>,listener=<listener>,networkProcessor=<processor>
Tip
|
The following Kafka broker metrics help monitor the performance of message down-conversion:
-
kafka.network:type=RequestMetrics,name=MessageConversionsTimeMs,request={Produce|Fetch} provides metrics on the time taken to perform message conversion.
-
kafka.server:type=BrokerTopicMetrics,name={Produce|Fetch}MessageConversionsPerSec,topic=([-.\w]+) provides metrics on the number of messages converted over a period of time.
|
Upgrade a ZooKeeper-based Kafka cluster to a newer supported Kafka version and inter-broker protocol version.
Prerequisites
-
The Cluster Operator is up and running.
-
Before you upgrade the Kafka cluster, check that the properties of the Kafka
resource do not contain configuration options that are not supported in the new Kafka version.
Procedure
-
Update the Kafka cluster configuration:
kubectl edit kafka <kafka_configuration_file>
-
If configured, check that the inter.broker.protocol.version
and log.message.format.version
properties are set to the current version.
For example, the current version is 3.7 if upgrading from Kafka version 3.7.0 to 3.8.0:
kind: Kafka
spec:
# ...
kafka:
version: 3.7.0
config:
log.message.format.version: "3.7"
inter.broker.protocol.version: "3.7"
# ...
If log.message.format.version
and inter.broker.protocol.version
are not configured,
Strimzi automatically updates these versions to the current defaults after the update to the Kafka version in the next step.
Note
|
The value of log.message.format.version and inter.broker.protocol.version must be strings to prevent them from being interpreted as floating point numbers.
|
-
Change the Kafka.spec.kafka.version
to specify the new Kafka version; leave the log.message.format.version
and inter.broker.protocol.version
at the defaults for the current Kafka version.
Note
|
Changing the kafka.version ensures that all brokers in the cluster are upgraded to start using the new broker binaries.
During this process, some brokers are using the old binaries while others have already upgraded to the new ones.
Leaving the inter.broker.protocol.version unchanged at the current setting ensures that the brokers can continue to communicate with each other throughout the upgrade.
|
For example, if upgrading from Kafka 3.7.0 to 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
# ...
kafka:
version: 3.8.0 (1)
config:
log.message.format.version: "3.7" (2)
inter.broker.protocol.version: "3.7" (3)
# ...
-
Kafka version is changed to the new version.
-
Message format version is unchanged.
-
Inter-broker protocol version is unchanged.
Warning
|
You cannot downgrade Kafka if the inter.broker.protocol.version for the new Kafka version changes. The inter-broker protocol version determines the schemas used for persistent metadata stored by the broker, including messages written to __consumer_offsets . The downgraded cluster will not understand the messages.
|
-
If the image for the Kafka cluster is defined in Kafka.spec.kafka.image
of the Kafka
custom resource, update the image
to point to a container image with the new Kafka version.
-
Save and exit the editor, then wait for rolling updates to complete.
Check the progress of the rolling updates by watching the pod state transitions:
kubectl get pods my-cluster-kafka-0 -o jsonpath='{.spec.containers[0].image}'
The rolling updates ensure that each pod is using the broker binaries for the new version of Kafka.
-
If required, set the version
property for Kafka Connect and MirrorMaker as the new version of Kafka:
-
For Kafka Connect, update KafkaConnect.spec.version
.
-
For MirrorMaker, update KafkaMirrorMaker.spec.version
.
-
For MirrorMaker 2, update KafkaMirrorMaker2.spec.version
.
Note
|
If you are using custom images that are built manually, you must rebuild those images to ensure that they are up-to-date with the latest Strimzi base image.
For example, if you created a container image from the base Kafka Connect image, update the Dockerfile to point to the latest base image and build configuration.
|
-
If configured, update the Kafka resource to use the new inter.broker.protocol.version
version. Otherwise, go to step 9.
For example, if upgrading to Kafka 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
# ...
kafka:
version: 3.8.0
config:
log.message.format.version: "3.7"
inter.broker.protocol.version: "3.8"
# ...
-
Wait for the Cluster Operator to update the cluster.
-
If configured, update the Kafka resource to use the new log.message.format.version
version. Otherwise, go to step 10.
For example, if upgrading to Kafka 3.8.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
# ...
kafka:
version: 3.8.0
config:
log.message.format.version: "3.8"
inter.broker.protocol.version: "3.8"
# ...
Important
|
From Kafka 3.0.0, when the inter.broker.protocol.version is set to 3.0 or higher, the log.message.format.version option is ignored and doesn’t need to be set.
|
-
Wait for the Cluster Operator to update the cluster.
Upgrading Kafka client applications
Ensure all Kafka client applications are updated to use the new version of the client binaries as part of the upgrade process and verify their compatibility with the Kafka upgrade.
If needed, coordinate with the team responsible for managing the client applications.
Tip
|
To check that a client is using the latest message format, use the kafka.server:type=BrokerTopicMetrics,name={Produce|Fetch}MessageConversionsPerSec metric.
The metric shows 0 if the latest message format is being used.
|
When performing an upgrade (or downgrade), you can check it completed successfully in the status of the Kafka
custom resource.
The status provides information on the Strimzi and Kafka versions being used.
To ensure that you have the correct versions after completing an upgrade, verify the kafkaVersion
and operatorLastSuccessfulVersion
values in the Kafka status.
-
operatorLastSuccessfulVersion
is the version of the Strimzi operator that last performed a successful reconciliation.
-
kafkaVersion
is the the version of Kafka being used by the Kafka cluster.
-
kafkaMetadataVersion
is the metadata version used by KRaft-based Kafka clusters
You can use these values to check an upgrade of Strimzi or Kafka has completed.
Checking an upgrade from the Kafka status
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
spec:
# ...
status:
# ...
kafkaVersion: 3.8.0
operatorLastSuccessfulVersion: 0.43.0
kafkaMetadataVersion: 3.8
Upgrade Strimzi to run in FIPS mode on FIPS-enabled Kubernetes clusters.
Until Strimzi 0.33, running on FIPS-enabled Kubernetes clusters was possible only by disabling FIPS mode using the FIPS_MODE
environment variable.
From release 0.33, Strimzi supports FIPS mode.
If you run Strimzi on a FIPS-enabled Kubernetes cluster with the FIPS_MODE
set to disabled
, you can enable it by following this procedure.
Procedure
-
Upgrade the Cluster Operator to version 0.33 or newer but keep the FIPS_MODE
environment variable set to disabled
.
-
If you initially deployed a Strimzi version older than 0.30, it might use old encryption and digest algorithms in its PKCS #12 stores, which are not supported with FIPS enabled.
To recreate the certificates with updated algorithms, renew the cluster and clients CA certificates.
-
If you use SCRAM-SHA-512 authentication, check the password length of your users.
If they are less than 32 characters long, generate a new password in one of the following ways:
-
Delete the user secret so that the User Operator generates a new one with a new password of sufficient length.
-
If you provided your password using the .spec.authentication.password
properties of the KafkaUser
custom resource, update the password in the Kubernetes secret referenced in the same password configuration.
Don’t forget to update your clients to use the new passwords.
-
Ensure that the CA certificates are using the correct algorithms and the SCRAM-SHA-512 passwords are of sufficient length.
You can then enable the FIPS mode.
-
Remove the FIPS_MODE
environment variable from the Cluster Operator deployment.
This restarts the Cluster Operator and rolls all the operands to enable the FIPS mode.
After the restart is complete, all Kafka clusters now run with FIPS mode enabled.
If you are encountering issues with the version of Strimzi you upgraded to,
you can revert your installation to the previous version.
If you used the YAML installation files to install Strimzi, you can use the YAML installation files from the previous release to perform the downgrade procedures.
You can downgrade Strimzi by updating the Cluster Operator and the version of Kafka you are using.
Kafka version downgrades are performed by the Cluster Operator.
Warning
|
The following downgrade instructions are only suitable if you installed Strimzi using the installation files.
If you installed Strimzi using another method, like OperatorHub.io, downgrade may not be supported by that method unless specified in their documentation.
To ensure a successful downgrade process, it is essential to use a supported approach.
|
If you are encountering issues with Strimzi,
you can revert your installation.
This procedure describes how to downgrade a Cluster Operator deployment to a previous version.
Before you begin
Check the downgrade requirements of the Strimzi feature gates.
If a feature gate is permanently enabled, you may need to downgrade to a version that allows you to disable it before downgrading to your target version.
Procedure
-
Take note of any configuration changes made during the previous Cluster Operator installation.
Any changes will be overwritten by the previous version of the Cluster Operator.
-
Revert your custom resources to reflect the supported configuration options available for the version of Strimzi you are downgrading to.
-
Update the Cluster Operator.
-
Modify the installation files for the previous version according to the namespace the Cluster Operator is running in.
sed -i 's/namespace: .*/namespace: my-cluster-operator-namespace/' install/cluster-operator/*RoleBinding*.yaml
sed -i '' 's/namespace: .*/namespace: my-cluster-operator-namespace/' install/cluster-operator/*RoleBinding*.yaml
-
If you modified one or more environment variables in your existing Cluster Operator Deployment
, edit the
install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
file to use those environment variables.
-
When you have an updated configuration, deploy it along with the rest of the installation resources:
kubectl replace -f install/cluster-operator
Wait for the rolling updates to complete.
-
Get the image for the Kafka pod to ensure the downgrade was successful:
kubectl get pod my-cluster-kafka-0 -o jsonpath='{.spec.containers[0].image}'
The image tag shows the new Strimzi version followed by the Kafka version.
For example, <strimzi_version>-kafka-<kafka_version>
.
Downgrade a KRaft-based Kafka cluster to an earlier version.
When downgrading a KRaft-based Kafka cluster to a lower version, like moving from 3.8.0 to 3.7.0, ensure that the metadata version used by the Kafka cluster is a version supported by the Kafka version you want to downgrade to.
The metadata version for the Kafka version you are downgrading from must not be higher than the version you are downgrading to.
Note
|
Consult the Apache Kafka documentation for information regarding the support and limitations associated with KRaft-based downgrades.
|
Prerequisites
-
The Cluster Operator is up and running.
-
Before you downgrade the Kafka cluster, check the following for the Kafka
resource:
-
The Kafka
custom resource does not contain options that are not supported by the Kafka version being downgraded to.
-
spec.kafka.metadataVersion
is set to a version that is supported by the Kafka version being downgraded to.
Procedure
-
Update the Kafka cluster configuration.
kubectl edit kafka <kafka_configuration_file>
-
Change the metadataVersion
version to a version supported by the Kafka version you are downgrading to; leave the Kafka.spec.kafka.version
unchanged at the current Kafka version.
For example, if downgrading from Kafka 3.8.0 to 3.7.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
metadataVersion: 3.7-IV4 # (1)
version: 3.8.0 # (2)
# ...
-
Metadata version is changed to a version supported by the earlier Kafka version.
-
Kafka version is unchanged.
Note
|
The value of metadataVersion must be a string to prevent it from being interpreted as a floating point number.
|
-
Save the change, and wait for Cluster Operator to update .status.kafkaMetadataVersion
for the Kafka
resource.
-
Change the Kafka.spec.kafka.version
to the previous version.
For example, if downgrading from Kafka 3.8.0 to 3.7.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
kafka:
replicas: 3
metadataVersion: 3.7-IV4 # (1)
version: 3.7.0 # (2)
# ...
-
Metadata version is supported by the Kafka version.
-
Kafka version is changed to the new version.
-
If the image for the Kafka version is different from the image defined in STRIMZI_KAFKA_IMAGES
for the Cluster Operator, update Kafka.spec.kafka.image
.
-
Wait for the Cluster Operator to update the cluster.
-
Downgrade all client applications (consumers) to use the previous version of the client binaries.
The Kafka cluster and clients are now using the previous Kafka version.
If you are using Kafka in ZooKeeper mode, the downgrade process involves changing the Kafka version and the related log.message.format.version
and inter.broker.protocol.version
properties.
Kafka downgrades are dependent on compatible current and target Kafka versions,
and the state at which messages have been logged.
You cannot revert to the previous Kafka version if that version does not support any of the inter.broker.protocol.version
settings which have ever been used in that cluster,
or messages have been added to message logs that use a newer log.message.format.version
.
The inter.broker.protocol.version
determines the schemas used for persistent metadata stored by the broker, such as the schema for messages written to __consumer_offsets
.
If you downgrade to a version of Kafka that does not understand an inter.broker.protocol.version
that has ever been previously used in the cluster the broker will encounter data it cannot understand.
If the target downgrade version of Kafka has:
-
The same log.message.format.version
as the current version, the Cluster Operator downgrades by performing a single rolling restart of the brokers.
-
A different log.message.format.version
, downgrading is only possible if the running cluster has always had log.message.format.version
set to the version used by the downgraded version.
This is typically only the case if the upgrade procedure was aborted before the log.message.format.version
was changed.
In this case, the downgrade requires:
Downgrading is not possible if the new version has ever used a log.message.format.version
that is not supported by the previous version, including when the default value for log.message.format.version
is used. For example, this resource can be downgraded to Kafka version 3.7.0 because the log.message.format.version
has not been changed:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
spec:
# ...
kafka:
version: 3.8.0
config:
log.message.format.version: "3.7"
# ...
The downgrade would not be possible if the log.message.format.version
was set at "3.8"
or a value was absent, so that the parameter took the default value for a 3.8.0 broker of 3.8.
Important
|
From Kafka 3.0.0, when the inter.broker.protocol.version is set to 3.0 or higher, the log.message.format.version option is ignored and doesn’t need to be set.
|
Downgrade a ZooKeeper-based Kafka cluster to an earlier version.
When downgrading a ZooKeeper-based Kafka cluster to a lower version, like moving from 3.8.0 to 3.7.0, ensure that the inter-broker protocol version used by the Kafka cluster is a version supported by the Kafka version you want to downgrade to.
The inter-broker protocol version for the Kafka version you are downgrading from must not be higher than the version you are downgrading to.
Note
|
Consult the Apache Kafka documentation for information regarding the support and limitations associated with ZooKeeper-based downgrades.
|
Prerequisites
-
The Cluster Operator is up and running.
-
Before you downgrade the Kafka cluster, check the following for the Kafka
resource:
-
IMPORTANT: Compatibility of Kafka versions.
-
The Kafka
custom resource does not contain options that are not supported by the Kafka version being downgraded to.
-
Kafka.spec.kafka.config
has a log.message.format.version
and inter.broker.protocol.version
that is supported by the Kafka version being downgraded to.
From Kafka 3.0.0, when the inter.broker.protocol.version
is set to 3.0
or higher, the log.message.format.version
option is ignored and doesn’t need to be set.
Procedure
-
Update the Kafka cluster configuration.
kubectl edit kafka <kafka_configuration_file>
-
Change the inter.broker.protocol.version
version (and log.message.format.version
, if applicable) to a version supported by the Kafka version you are downgrading to; leave the Kafka.spec.kafka.version
unchanged at the current Kafka version.
For example, if downgrading from Kafka 3.8.0 to 3.7.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
# ...
kafka:
version: 3.8.0 (1)
config:
inter.broker.protocol.version: "3.7" (2)
log.message.format.version: "3.7"
# ...
-
Kafka version is unchanged.
-
Inter-broker protocol version is changed to a version supported by the earlier Kafka version.
Note
|
The value of log.message.format.version and inter.broker.protocol.version must be strings to prevent them from being interpreted as floating point numbers.
|
-
Save and exit the editor, then wait for rolling updates to complete.
Check the progress of the rolling updates by watching the pod state transitions:
kubectl get pods my-cluster-kafka-0 -o jsonpath='{.spec.containers[0].image}'
The rolling updates ensure that each pod is using the specified Kafka inter-broker protocol version.
-
Change the Kafka.spec.kafka.version
to the previous version.
For example, if downgrading from Kafka 3.8.0 to 3.7.0:
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: my-cluster
spec:
# ...
kafka:
version: 3.7.0 (1)
config:
inter.broker.protocol.version: "3.7" (2)
log.message.format.version: "3.7"
# ...
-
Kafka version is changed to the new version.
-
Inter-broker protocol version is supported by the Kafka version.
-
If the image for the Kafka version is different from the image defined in STRIMZI_KAFKA_IMAGES
for the Cluster Operator, update Kafka.spec.kafka.image
.
-
Wait for the Cluster Operator to update the cluster.
-
Downgrade all client applications (consumers) to use the previous version of the client binaries.
The Kafka cluster and clients are now using the previous Kafka version.
-
If you are reverting back to a version of Strimzi earlier than 0.22, which uses ZooKeeper for the storage of topic metadata, delete the internal topic store topics from the Kafka cluster.
kubectl run kafka-admin -ti --image=quay.io/strimzi/kafka:0.43.0-kafka-3.8.0 --rm=true --restart=Never -- ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi-topic-operator-kstreams-topic-store-changelog --delete && ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic __strimzi_store_topic --delete
You can uninstall Strimzi using the CLI or by unsubscribing from OperatorHub.io.
Use the same approach you used to install Strimzi.
When you uninstall Strimzi, you will need to identify resources created specifically for a deployment and referenced from the Strimzi resource.
-
Secrets (Custom CAs and certificates, Kafka Connect secrets, and other Kafka secrets)
-
Logging ConfigMaps
(of type external
)
These are resources referenced by Kafka
, KafkaConnect
, KafkaMirrorMaker
, or KafkaBridge
configuration.
Warning
|
Deleting CRDs and related custom resources
When a CustomResourceDefinition is deleted, custom resources of that type are also deleted.
This includes the Kafka , KafkaConnect , KafkaMirrorMaker , and KafkaBridge resources managed by Strimzi, as well as the StrimziPodSet resource Strimzi uses to manage the pods of the Kafka components.
In addition, any Kubernetes resources created by these custom resources, such as Deployment , Pod , Service , and ConfigMap resources, are also removed.
Always exercise caution when deleting these resources to avoid unintended data loss.
|
This procedure describes how to use the kubectl
command-line tool to uninstall Strimzi and remove resources related to the deployment.
Procedure
-
Delete the Cluster Operator Deployment
, related CustomResourceDefinitions
, and RBAC
resources.
Specify the installation files used to deploy the Cluster Operator.
kubectl delete -f install/cluster-operator
-
Delete the resources you identified in the prerequisites.
kubectl delete <resource_type> <resource_name> -n <namespace>
Replace <resource_type> with the type of resource you are deleting and <resource_name> with the name of the resource.
Example to delete a secret
kubectl delete secret my-cluster-clients-ca-cert -n my-project
This procedure describes how to uninstall Strimzi from OperatorHub.io and remove resources related to the deployment.
You perform the steps using the kubectl
command-line tool.
Procedure
-
Delete the Strimzi subscription.
kubectl delete subscription strimzi-cluster-operator -n <namespace>
-
Delete the cluster service version (CSV).
kubectl delete csv strimzi-cluster-operator.<version> -n <namespace>
-
Remove related CRDs.
kubectl get crd -l app=strimzi -o name | xargs kubectl delete
You can recover a Kafka cluster from persistent volumes (PVs) if they are still present.
Recovering from PVs is possible in the following scenarios:
The recovery procedure for both scenarios is to recreate the original PersistentVolumeClaim
(PVC) resources.
When you delete a namespace, all resources within that namespace—including PVCs, pods, and services—are deleted.
If the reclaimPolicy
for the PV resource specification is set to Retain
, the PV retains its data and is not deleted.
This configuration allows you to recover from namespace deletion.
PV configuration to retain data
apiVersion: v1
kind: PersistentVolume
# ...
spec:
# ...
persistentVolumeReclaimPolicy: Retain
Alternatively, PVs can inherit the reclaim policy from an associated storage class.
Storage classes are used for dynamic volume allocation.
By configuring the reclaimPolicy
property for the storage class, PVs created with this class use the specified reclaim policy.
The storage class is assigned to the PV using the storageClassName
property.
Storage class configuration to retain data
apiVersion: v1
kind: StorageClass
metadata:
name: gp2-retain
parameters:
# ...
# ...
reclaimPolicy: Retain
Storage class specified for PV
apiVersion: v1
kind: PersistentVolume
# ...
spec:
# ...
storageClassName: gp2-retain
Note
|
When using Retain as the reclaim policy, you must manually delete PVs if you intend to delete the entire cluster.
|
If you lose the entire Kubernetes cluster, all resources—including PVs, PVCs, and namespaces—are lost.
However, it’s possible to recover if the physical storage backing the PVs remains intact.
To recover, you need to set up a new Kubernetes cluster and manually reconfigure the PVs to use the existing storage.
This procedure describes how to recover a deleted cluster from persistent volumes (PVs) by recreating the original PersistentVolumeClaim
(PVC) resources.
If the Topic Operator and User Operator are deployed, you can recover KafkaTopic
and KafkaUser
resources by recreating them.
It is important that you recreate the KafkaTopic
resources with the same configurations, or the Topic Operator will try to update them in Kafka.
This procedure shows how to recreate both resources.
Warning
|
If the User Operator is enabled and Kafka users are not recreated, users are deleted from the Kafka cluster immediately after recovery.
|
Before you begin
In this procedure, it is essential that PVs are mounted into the correct PVC to avoid data corruption.
A volumeName
is specified for the PVC and this must match the name of the PV.
Procedure
-
Check information on the PVs in the cluster:
Information is presented for PVs with data.
Example PV output
NAME RECLAIMPOLICY CLAIM
pvc-5e9c5c7f-3317-11ea-a650-06e1eadd9a4c ... Retain ... myproject/data-my-cluster-zookeeper-1
pvc-5e9cc72d-3317-11ea-97b0-0aef8816c7ea ... Retain ... myproject/data-my-cluster-zookeeper-0
pvc-5ead43d1-3317-11ea-97b0-0aef8816c7ea ... Retain ... myproject/data-my-cluster-zookeeper-2
pvc-7e1f67f9-3317-11ea-a650-06e1eadd9a4c ... Retain ... myproject/data-0-my-cluster-kafka-0
pvc-7e21042e-3317-11ea-9786-02deaf9aa87e ... Retain ... myproject/data-0-my-cluster-kafka-1
pvc-7e226978-3317-11ea-97b0-0aef8816c7ea ... Retain ... myproject/data-0-my-cluster-kafka-2
-
NAME
is the name of each PV.
-
RECLAIMPOLICY
shows that PVs are retained, meaning that the PV is not automatically deleted when the PVC is deleted.
-
CLAIM
shows the link to the original PVCs.
-
Recreate the original namespace:
kubectl create namespace my-project
Here, we recreate the my-project
namespace.
-
Recreate the original PVC resource specifications, linking the PVCs to the appropriate PV:
Example PVC resource specification
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: data-0-my-cluster-kafka-0
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 100Gi
storageClassName: gp2-retain
volumeMode: Filesystem
volumeName: pvc-7e1f67f9-3317-11ea-a650-06e1eadd9a4c
-
Edit the PV specifications to delete the claimRef
properties that bound the original PVC.
Example PV specification
apiVersion: v1
kind: PersistentVolume
metadata:
annotations:
kubernetes.io/createdby: aws-ebs-dynamic-provisioner
pv.kubernetes.io/bound-by-controller: "yes"
pv.kubernetes.io/provisioned-by: kubernetes.io/aws-ebs
creationTimestamp: "<date>"
finalizers:
- kubernetes.io/pv-protection
labels:
failure-domain.beta.kubernetes.io/region: eu-west-1
failure-domain.beta.kubernetes.io/zone: eu-west-1c
name: pvc-7e226978-3317-11ea-97b0-0aef8816c7ea
resourceVersion: "39431"
selfLink: /api/v1/persistentvolumes/pvc-7e226978-3317-11ea-97b0-0aef8816c7ea
uid: 7efe6b0d-3317-11ea-a650-06e1eadd9a4c
spec:
accessModes:
- ReadWriteOnce
awsElasticBlockStore:
fsType: xfs
volumeID: aws://eu-west-1c/vol-09db3141656d1c258
capacity:
storage: 100Gi
claimRef:
apiVersion: v1
kind: PersistentVolumeClaim
name: data-0-my-cluster-kafka-2
namespace: myproject
resourceVersion: "39113"
uid: 54be1c60-3319-11ea-97b0-0aef8816c7ea
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: failure-domain.beta.kubernetes.io/zone
operator: In
values:
- eu-west-1c
- key: failure-domain.beta.kubernetes.io/region
operator: In
values:
- eu-west-1
persistentVolumeReclaimPolicy: Retain
storageClassName: gp2-retain
volumeMode: Filesystem
In the example, the following properties are deleted:
claimRef:
apiVersion: v1
kind: PersistentVolumeClaim
name: data-0-my-cluster-kafka-2
namespace: myproject
resourceVersion: "39113"
uid: 54be1c60-3319-11ea-97b0-0aef8816c7ea
-
Deploy the Cluster Operator:
kubectl create -f install/cluster-operator -n my-project
-
Recreate all KafkaTopic
resources by applying the KafkaTopic
resource configuration:
kubectl apply -f <topic_configuration_file>
-
Recreate all KafkaUser
resources:
-
If user passwords and certificates need to be retained, recreate the user secrets before recreating the KafkaUser
resources.
If the secrets are not recreated, the User Operator will generate new credentials automatically.
Ensure that the recreated secrets have exactly the same name, labels, and fields as the original secrets.
-
Apply the KafkaUser
resource configuration:
kubectl apply -f <user_configuration_file>
-
Deploy the Kafka cluster using the original configuration for the Kafka
resource:
kubectl apply -f <kafka_resource_configuration>.yaml -n my-project
-
Verify the recovery of the KafkaTopic
resources:
kubectl get kafkatopics -o wide -w -n my-project
Kafka topic status
NAME CLUSTER PARTITIONS REPLICATION FACTOR READY
my-topic-1 my-cluster 10 3 True
my-topic-2 my-cluster 10 3 True
my-topic-3 my-cluster 10 3 True
KafkaTopic
custom resource creation is successful when the READY
output shows True
.
-
Verify the recovery of the KafkaUser
resources:
kubectl get kafkausers -o wide -w -n my-project
Kafka user status
NAME CLUSTER AUTHENTICATION AUTHORIZATION READY
my-user-1 my-cluster tls simple True
my-user-2 my-cluster tls simple True
my-user-3 my-cluster tls simple True
KafkaUser
custom resource creation is successful when the READY
output shows True
.
Fine-tuning the performance of your Kafka deployment involves optimizing various configuration properties according to your specific requirements.
This section provides an introduction to common configuration options available for Kafka brokers, producers, and consumers.
While a minimum set of configurations is necessary for Kafka to function, Kafka properties allow for extensive adjustments.
Through configuration properties, you can enhance latency, throughput, and overall efficiency, ensuring that your Kafka deployment meets the demands of your applications.
For effective tuning, take a methodical approach.
Begin by analyzing relevant metrics to identify potential bottlenecks or areas for improvement.
Adjust configuration parameters iteratively, monitoring the impact on performance metrics, and then refine your settings accordingly.
Note
|
The guidance provided here offers a starting point for tuning your Kafka deployment.
Finding the optimal configuration depends on factors such as workload, infrastructure, and performance objectives.
|
The following tools help with Kafka tuning:
-
Cruise Control generates optimization proposals that you can use to assess and implement a cluster rebalance
-
Strimzi Quotas plugin sets limits on brokers
-
Rack configuration spreads broker partitions across racks and allows consumers to fetch data from the nearest replica
When you deploy Strimzi on Kubernetes, you can specify broker configuration through the config
property of the Kafka
custom resource.
However, certain broker configuration options are managed directly by Strimzi.
As such, you cannot configure the following options:
-
broker.id
to specify the ID of the Kafka broker
-
log.dirs
directories for log data
-
zookeeper.connect
configuration to connect Kafka with ZooKeeper
-
listeners
to expose the Kafka cluster to clients
-
authorization
mechanisms to allow or decline actions executed by users
-
authentication
mechanisms to prove the identity of users requiring access to Kafka
Broker IDs start from 0 (zero) and correspond to the number of broker replicas.
Log directories are mounted to /var/lib/kafka/data/kafka-logIDX
based on the spec.kafka.storage
configuration in the Kafka
custom resource.
IDX is the Kafka broker pod index.
Use configuration properties to optimize the performance of Kafka brokers.
You can use standard Kafka broker configuration options, except for properties managed directly by Strimzi.
A typical broker configuration will include settings for properties related to topics, threads and logs.
Basic broker configuration properties
# ...
num.partitions=1
default.replication.factor=3
offsets.topic.replication.factor=3
transaction.state.log.replication.factor=3
transaction.state.log.min.isr=2
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
num.network.threads=3
num.io.threads=8
num.recovery.threads.per.data.dir=1
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
group.initial.rebalance.delay.ms=0
zookeeper.connection.timeout.ms=6000
# ...
Basic topic properties set the default number of partitions and replication factor for topics, which will apply to topics that are created without these properties being explicitly set, including when topics are created automatically.
# ...
num.partitions=1
auto.create.topics.enable=false
default.replication.factor=3
min.insync.replicas=2
replica.fetch.max.bytes=1048576
# ...
For high availability environments, it is advisable to increase the replication factor to at least 3 for topics and set the minimum number of in-sync replicas required to 1 less than the replication factor.
The auto.create.topics.enable
property is enabled by default so that topics that do not already exist are created automatically when needed by producers and consumers.
If you are using automatic topic creation, you can set the default number of partitions for topics using num.partitions
.
Generally, however, this property is disabled so that more control is provided over topics through explicit topic creation.
For data durability, you should also set min.insync.replicas
in your topic configuration and message delivery acknowledgments using acks=all
in your producer configuration.
Use replica.fetch.max.bytes
to set the maximum size, in bytes, of messages fetched by each follower that replicates the leader partition.
Change this value according to the average message size and throughput. When considering the total memory allocation required for read/write buffering, the memory available must also be able to accommodate the maximum replicated message size when multiplied by all followers.
The delete.topic.enable
property is enabled by default to allow topics to be deleted.
In a production environment, you should disable this property to avoid accidental topic deletion, resulting in data loss.
You can, however, temporarily enable it and delete topics and then disable it again.
Note
|
When running Strimzi on Kubernetes, the Topic Operator can provide operator-style topic management. You can use the KafkaTopic resource to create topics.
For topics created using the KafkaTopic resource, the replication factor is set using spec.replicas .
If delete.topic.enable is enabled, you can also delete topics using the KafkaTopic resource.
|
# ...
auto.create.topics.enable=false
delete.topic.enable=true
# ...
If you are using transactions to enable atomic writes to partitions from producers, the state of the transactions is stored in the internal __transaction_state
topic.
By default, the brokers are configured with a replication factor of 3 and a minimum of 2 in-sync replicas for this topic, which means that a minimum of three brokers are required in your Kafka cluster.
# ...
transaction.state.log.replication.factor=3
transaction.state.log.min.isr=2
# ...
Similarly, the internal __consumer_offsets
topic, which stores consumer state, has default settings for the number of partitions and replication factor.
# ...
offsets.topic.num.partitions=50
offsets.topic.replication.factor=3
# ...
Do not reduce these settings in production.
You can increase the settings in a production environment.
As an exception, you might want to reduce the settings in a single-broker test environment.
Network threads handle requests to the Kafka cluster, such as produce and fetch requests from client applications.
Produce requests are placed in a request queue. Responses are placed in a response queue.
The number of network threads per listener should reflect the replication factor and the levels of activity from client producers and consumers interacting with the Kafka cluster.
If you are going to have a lot of requests, you can increase the number of threads, using the amount of time threads are idle to determine when to add more threads.
To reduce congestion and regulate the request traffic, you can limit the number of requests allowed in the request queue.
When the request queue is full, all incoming traffic is blocked.
I/O threads pick up requests from the request queue to process them.
Adding more threads can improve throughput, but the number of CPU cores and disk bandwidth imposes a practical upper limit.
At a minimum, the number of I/O threads should equal the number of storage volumes.
# ...
num.network.threads=3 (1)
queued.max.requests=500 (2)
num.io.threads=8 (3)
num.recovery.threads.per.data.dir=4 (4)
# ...
-
The number of network threads for the Kafka cluster.
-
The number of requests allowed in the request queue.
-
The number of I/O threads for a Kafka broker.
-
The number of threads used for log loading at startup and flushing at shutdown. Try setting to a value of at least the number of cores.
Configuration updates to the thread pools for all brokers might occur dynamically at the cluster level.
These updates are restricted to between half the current size and twice the current size.
Tip
|
The following Kafka broker metrics can help with working out the number of threads required:
-
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent provides metrics on the average time network threads are idle as a percentage.
-
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent provides metrics on the average time I/O threads are idle as a percentage.
If there is 0% idle time, all resources are in use, which means that adding more threads might be beneficial.
When idle time goes below 30%, performance may start to suffer.
|
If threads are slow or limited due to the number of disks, you can try increasing the size of the buffers for network requests to improve throughput:
# ...
replica.socket.receive.buffer.bytes=65536
# ...
And also increase the maximum number of bytes Kafka can receive:
# ...
socket.request.max.bytes=104857600
# ...
Kafka batches data to achieve reasonable throughput over high-latency connections from Kafka to clients, such as connections between datacenters.
However, if high latency is a problem, you can increase the size of the buffers for sending and receiving messages.
# ...
socket.send.buffer.bytes=1048576
socket.receive.buffer.bytes=1048576
# ...
You can estimate the optimal size of your buffers using a bandwidth-delay product calculation,
which multiplies the maximum bandwidth of the link (in bytes/s) with the round-trip delay (in seconds) to give an estimate of how large a buffer is required to sustain maximum throughput.
Kafka relies on logs to store message data.
A log consists of a series of segments, where each segment is associated with offset-based and timestamp-based indexes.
New messages are written to an active segment and are never subsequently modified.
When serving fetch requests from consumers, the segments are read.
Periodically, the active segment is rolled to become read-only, and a new active segment is created to replace it.
There is only one active segment per topic-partition per broker.
Older segments are retained until they become eligible for deletion.
Configuration at the broker level determines the maximum size in bytes of a log segment and the time in milliseconds before an active segment is rolled:
# ...
log.segment.bytes=1073741824
log.roll.ms=604800000
# ...
These settings can be overridden at the topic level using segment.bytes
and segment.ms
.
The choice to lower or raise these values depends on the policy for segment deletion.
A larger size means the active segment contains more messages and is rolled less often.
Segments also become eligible for deletion less frequently.
In Kafka, log cleanup policies determine how log data is managed.
In most cases, you won’t need to change the default configuration at the cluster level, which specifies the delete
cleanup policy and enables the log cleaner used by the compact
cleanup policy:
# ...
log.cleanup.policy=delete
log.cleaner.enable=true
# ...
- Delete cleanup policy
-
Delete cleanup policy is the default cluster-wide policy for all topics.
The policy is applied to topics that do not have a specific topic-level policy configured.
Kafka removes older segments based on time-based or size-based log retention limits.
- Compact cleanup policy
-
Compact cleanup policy is generally configured as a topic-level policy (cleanup.policy=compact
).
Kafka’s log cleaner applies compaction on specific topics, retaining only the most recent value for a key in the topic.
You can also configure topics to use both policies (cleanup.policy=compact,delete
).
Setting up retention limits for the delete policy
Delete cleanup policy corresponds to managing logs with data retention.
The policy is suitable when data does not need to be retained forever.
You can establish time-based or size-based log retention and cleanup policies to keep logs bounded.
When log retention policies are employed, non-active log segments are removed when retention limits are reached.
Deletion of old segments helps to prevent exceeding disk capacity.
For time-based log retention, you set a retention period based on hours, minutes, or milliseconds:
# ...
log.retention.ms=1680000
# ...
The retention period is based on the time messages were appended to the segment.
Kafka uses the timestamp of the latest message within a segment to determine if that segment has expired or not.
The milliseconds configuration has priority over minutes, which has priority over hours.
The minutes and milliseconds configurations are null by default, but the three options provide a substantial level of control over the data you wish to retain.
Preference should be given to the milliseconds configuration, as it is the only one of the three properties that is dynamically updateable.
If log.retention.ms
is set to -1, no time limit is applied to log retention, and all logs are retained.
However, this setting is not generally recommended as it can lead to issues with full disks that are difficult to rectify.
For size-based log retention, you specify a minimum log size (in bytes):
# ...
log.retention.bytes=1073741824
# ...
This means that Kafka will ensure there is always at least the specified amount of log data available.
For example, if you set log.retention.bytes
to 1000 and log.segment.bytes
to 300, Kafka will keep 4 segments plus the active segment, ensuring a minimum of 1000 bytes are available.
When the active segment becomes full and a new segment is created, the oldest segment is deleted.
At this point, the size on disk may exceed the specified 1000 bytes, potentially ranging between 1200 and 1500 bytes (excluding index files).
A potential issue with using a log size is that it does not take into account the time messages were appended to a segment.
You can use time-based and size-based log retention for your cleanup policy to get the balance you need.
Whichever threshold is reached first triggers the cleanup.
To add a time delay before a segment file is deleted from the system, you can use log.segment.delete.delay.ms
at the broker level for all topics:
# ...
log.segment.delete.delay.ms=60000
# ...
Or configure file.delete.delay.ms
at the topic level.
You set the frequency at which the log is checked for cleanup in milliseconds:
# ...
log.retention.check.interval.ms=300000
# ...
Adjust the log retention check interval in relation to the log retention settings.
Smaller retention sizes might require more frequent checks.
The frequency of cleanup should be often enough to manage the disk space but not so often it affects performance on a broker.
Retaining the most recent messages using compact policy
When you enable log compaction for a topic by setting cleanup.policy=compact
, Kafka uses the log cleaner as a background thread to perform the compaction.
The compact policy guarantees that the most recent message for each message key is retained, effectively cleaning up older versions of records.
The policy is suitable when message values are changeable, and you want to retain the latest update.
If a cleanup policy is set for log compaction, the head of the log operates as a standard Kafka log, with writes for new messages appended in order.
In the tail of a compacted log, where the log cleaner operates, records are deleted if another record with the same key occurs later in the log.
Messages with null values are also deleted.
To use compaction, you must have keys to identify related messages because Kafka guarantees that the latest messages for each key will be retained, but it does not guarantee that the whole compacted log will not contain duplicates.
Figure 8. Log showing key value writes with offset positions before compaction
Using keys to identify messages, Kafka compaction keeps the latest message (with the highest offset) that is present in the log tail for a specific message key, eventually discarding earlier messages that have the same key.
The message in its latest state is always available, and any out-of-date records of that particular message are eventually removed when the log cleaner runs.
You can restore a message back to a previous state.
Records retain their original offsets even when surrounding records get deleted.
Consequently, the tail can have non-contiguous offsets.
When consuming an offset that’s no longer available in the tail, the record with the next higher offset is found.
Figure 9. Log after compaction
If appropriate, you can add a delay to the compaction process:
# ...
log.cleaner.delete.retention.ms=86400000
# ...
The deleted data retention period gives time to notice the data is gone before it is irretrievably deleted.
To delete all messages related to a specific key, a producer can send a tombstone message.
A tombstone has a null value and acts as a marker to inform consumers that the corresponding message for that key has been deleted.
After some time, only the tombstone marker is retained.
Assuming new messages continue to come in, the marker is retained for a duration specified by log.cleaner.delete.retention.ms
to allow consumers enough time to recognize the deletion.
You can also set a time in milliseconds to put the cleaner on standby if there are no logs to clean:
# ...
log.cleaner.backoff.ms=15000
# ...
Using combined compact and delete policies
If you choose only a compact policy, your log can still become arbitrarily large.
In such cases, you can set the cleanup policy for a topic to compact and delete logs.
Kafka applies log compaction, removing older versions of records and retaining only the latest version of each key.
Kafka also deletes records based on the specified time-based or size-based log retention settings.
For example, in the following diagram only the latest message (with the highest offset) for a specific message key is retained up to the compaction point.
If there are any records remaining up to the retention point they are deleted.
In this case, the compaction process would remove all duplicates.
Figure 10. Log retention point and compaction point
When employing the compact policy and log cleaner to handle topic logs in Kafka, consider optimizing memory allocation.
You can fine-tune memory allocation using the deduplication property (dedupe.buffer.size
), which determines the total memory allocated for cleanup tasks across all log cleaner threads.
Additionally, you can establish a maximum memory usage limit by defining a percentage through the buffer.load.factor
property.
# ...
log.cleaner.dedupe.buffer.size=134217728
log.cleaner.io.buffer.load.factor=0.9
# ...
Each log entry uses exactly 24 bytes, so you can work out how many log entries the buffer can handle in a single run and adjust the setting accordingly.
If possible, consider increasing the number of log cleaner threads if you are looking to reduce the log cleaning time:
# ...
log.cleaner.threads=8
# ...
If you are experiencing issues with 100% disk bandwidth usage, you can throttle the log cleaner I/O so that the sum of the read/write operations is less than a specified double value based on the capabilities of the disks performing the operations:
# ...
log.cleaner.io.max.bytes.per.second=1.7976931348623157E308
# ...
Generally, the recommendation is to not set explicit flush thresholds and let the operating system perform background flush using its default settings.
Partition replication provides greater data durability than writes to any single disk, as a failed broker can recover from its in-sync replicas.
Log flush properties control the periodic writes of cached message data to disk.
The scheduler specifies the frequency of checks on the log cache in milliseconds:
# ...
log.flush.scheduler.interval.ms=2000
# ...
You can control the frequency of the flush based on the maximum amount of time that a message is kept in-memory and the maximum number of messages in the log before writing to disk:
# ...
log.flush.interval.ms=50000
log.flush.interval.messages=100000
# ...
The wait between flushes includes the time to make the check and the specified interval before the flush is carried out.
Increasing the frequency of flushes can affect throughput.
If you are using application flush management, setting lower flush thresholds might be appropriate if you are using faster disks.
Partitions can be replicated across brokers for fault tolerance.
For a given partition, one broker is elected leader and handles all produce requests (writes to the log).
Partition followers on other brokers replicate the partition data of the partition leader for data reliability in the event of the leader failing.
Followers do not normally serve clients, though rack
configuration allows a consumer to consume messages from the closest replica when a Kafka cluster spans multiple datacenters.
Followers operate only to replicate messages from the partition leader and allow recovery should the leader fail.
Recovery requires an in-sync follower. Followers stay in sync by sending fetch requests to the leader, which returns messages to the follower in order.
The follower is considered to be in sync if it has caught up with the most recently committed message on the leader.
The leader checks this by looking at the last offset requested by the follower.
An out-of-sync follower is usually not eligible as a leader should the current leader fail, unless unclean leader election is allowed.
You can adjust the lag time before a follower is considered out of sync:
# ...
replica.lag.time.max.ms=30000
# ...
Lag time puts an upper limit on the time to replicate a message to all in-sync replicas and how long a producer has to wait for an acknowledgment.
If a follower fails to make a fetch request and catch up with the latest message within the specified lag time, it is removed from in-sync replicas.
You can reduce the lag time to detect failed replicas sooner, but by doing so you might increase the number of followers that fall out of sync needlessly.
The right lag time value depends on both network latency and broker disk bandwidth.
When a leader partition is no longer available, one of the in-sync replicas is chosen as the new leader.
The first broker in a partition’s list of replicas is known as the preferred leader.
By default, Kafka is enabled for automatic partition leader rebalancing based on a periodic check of leader distribution.
That is, Kafka checks to see if the preferred leader is the current leader.
A rebalance ensures that leaders are evenly distributed across brokers and brokers are not overloaded.
You can use Cruise Control for Strimzi to figure out replica assignments to brokers that balance load evenly across the cluster.
Its calculation takes into account the differing load experienced by leaders and followers.
A failed leader affects the balance of a Kafka cluster because the remaining brokers get the extra work of leading additional partitions.
For the assignment found by Cruise Control to actually be balanced it is necessary that partitions are lead by the preferred leader. Kafka can automatically ensure that the preferred leader is being used (where possible), changing the current leader if necessary. This ensures that the cluster remains in the balanced state found by Cruise Control.
You can control the frequency, in seconds, of the rebalance check and the maximum percentage of imbalance allowed for a broker before a rebalance is triggered.
#...
auto.leader.rebalance.enable=true
leader.imbalance.check.interval.seconds=300
leader.imbalance.per.broker.percentage=10
#...
The percentage leader imbalance for a broker is the ratio between the current number of partitions for which the broker is the current leader and the number of partitions for which it is the preferred leader.
You can set the percentage to zero to ensure that preferred leaders are always elected, assuming they are in sync.
If the checks for rebalances need more control, you can disable automated rebalances. You can then choose when to trigger a rebalance using the kafka-leader-election.sh
command line tool.
Note
|
The Grafana dashboards provided with Strimzi show metrics for under-replicated partitions and partitions that do not have an active leader.
|
Leader election to an in-sync replica is considered clean because it guarantees no loss of data. And this is what happens by default.
But what if there is no in-sync replica to take on leadership? Perhaps the ISR (in-sync replica) only contained the leader when the leader’s disk died. If a minimum number of in-sync replicas is not set, and there are no followers in sync with the partition leader when its hard drive fails irrevocably, data is already lost.
Not only that, but a new leader cannot be elected because there are no in-sync followers.
You can configure how Kafka handles leader failure:
# ...
unclean.leader.election.enable=false
# ...
Unclean leader election is disabled by default, which means that out-of-sync replicas cannot become leaders.
With clean leader election, if no other broker was in the ISR when the old leader was lost, Kafka waits until that leader is back online before messages can be written or read.
Unclean leader election means out-of-sync replicas can become leaders, but you risk losing messages.
The choice you make depends on whether your requirements favor availability or durability.
You can override the default configuration for specific topics at the topic level.
If you cannot afford the risk of data loss, then leave the default configuration.
For consumers joining a new consumer group, you can add a delay so that unnecessary rebalances to the broker are avoided:
# ...
group.initial.rebalance.delay.ms=3000
# ...
The delay is the amount of time that the coordinator waits for members to join. The longer the delay,
the more likely it is that all the members will join in time and avoid a rebalance.
But the delay also prevents the group from consuming until the period has ended.
Use configuration properties to optimize the performance of Kafka producers.
You can use standard Kafka producer configuration options.
Adjusting your configuration to maximize throughput might increase latency or vice versa.
You will need to experiment and tune your producer configuration to get the balance you need.
When configuring a producer, consider the following aspects carefully, as they significantly impact its performance and behavior:
- Compression
-
By compressing messages before they are sent over the network, you can conserve network bandwidth and reduce disk storage requirements, but with the additional cost of increased CPU utilization due to the compression and decompression processes.
- Batching
-
Adjusting the batch size and time intervals when the producer sends messages can affect throughput and latency.
- Partitioning
-
Partitioning strategies in the Kafka cluster can support producers through parallelism and load balancing, whereby producers can write to multiple partitions concurrently and each partition receives an equal share of messages. Other strategies might include topic replication for fault tolerance.
- Securing access
-
Implement security measures for authentication, encryption, and authorization by setting up user accounts to manage secure access to Kafka.
Connection and serializer properties are required for every producer.
Generally, it is good practice to add a client id for tracking,
and use compression on the producer to reduce batch sizes in requests.
In a basic producer configuration:
Basic producer configuration properties
# ...
bootstrap.servers=localhost:9092 (1)
key.serializer=org.apache.kafka.common.serialization.StringSerializer (2)
value.serializer=org.apache.kafka.common.serialization.StringSerializer (3)
client.id=my-client (4)
compression.type=gzip (5)
# ...
-
(Required) Tells the producer to connect to a Kafka cluster using a host:port bootstrap server address for a Kafka broker.
The producer uses the address to discover and connect to all brokers in the cluster.
Use a comma-separated list to specify two or three addresses in case a server is down, but it’s not necessary to provide a list of all the brokers in the cluster.
-
(Required) Serializer to transform the key of each message to bytes prior to them being sent to a broker.
-
(Required) Serializer to transform the value of each message to bytes prior to them being sent to a broker.
-
(Optional) The logical name for the client, which is used in logs and metrics to identify the source of a request.
-
(Optional) The codec for compressing messages, which are sent and might be stored in compressed format and then decompressed when reaching a consumer.
Compression is useful for improving throughput and reducing the load on storage, but might not be suitable for low latency applications where the cost of compression or decompression could be prohibitive.
Message delivery acknowledgments minimize the likelihood that messages are lost.
By default, acknowledgments are enabled with the acks property set to acks=all
.
To control the maximum time the producer waits for acknowledgments from the broker and handle potential delays in sending messages, you can use the delivery.timeout.ms
property.
Acknowledging message delivery
# ...
acks=all (1)
delivery.timeout.ms=120000 (2)
# ...
-
acks=all
forces a leader replica to replicate messages to a certain number of followers before
acknowledging that the message request was successfully received.
-
The maximum time in milliseconds to wait for a complete send request.
You can set the value to MAX_LONG
to delegate to Kafka an indefinite number of retries.
The default is 120000
or 2 minutes.
The acks=all
setting offers the strongest guarantee of delivery, but it will increase the latency between the producer sending a message and receiving acknowledgment.
If you don’t require such strong guarantees, a setting of acks=0
or acks=1
provides either no delivery guarantees or only acknowledgment that the leader replica has written the record to its log.
With acks=all
, the leader waits for all in-sync replicas to acknowledge message delivery.
A topic’s min.insync.replicas
configuration sets the minimum required number of in-sync replica acknowledgements.
The number of acknowledgements include that of the leader and followers.
A typical starting point is to use the following configuration:
When you create a topic, you can override the default replication factor.
You can also override min.insync.replicas
at the topic level in the topic configuration.
Strimzi uses this configuration in the example configuration files for multi-node deployment of Kafka.
The following table describes how this configuration operates depending on the availability of followers that replicate the leader replica.
Table 43. Follower availability
Number of followers available and in-sync |
Acknowledgements |
Producer can send messages? |
2 |
The leader waits for 2 follower acknowledgements |
Yes |
1 |
The leader waits for 1 follower acknowledgement |
Yes |
0 |
The leader raises an exception |
No |
A topic replication factor of 3 creates one leader replica and two followers.
In this configuration, the producer can continue if a single follower is unavailable.
Some delay can occur whilst removing a failed broker from the in-sync replicas or a creating a new leader.
If the second follower is also unavailable, message delivery will not be successful.
Instead of acknowledging successful message delivery, the leader sends an error (not enough replicas) to the producer.
The producer raises an equivalent exception.
With retries
configuration, the producer can resend the failed message request.
Note
|
If the system fails, there is a risk of unsent data in the buffer being lost.
|
Idempotent producers avoid duplicates as messages are delivered exactly once.
IDs and sequence numbers are assigned to messages to ensure the order of delivery, even in the event of failure.
If you are using acks=all
for data consistency, using idempotency makes sense for ordered delivery.
Idempotency is enabled for producers by default.
With idempotency enabled, you can set the number of concurrent in-flight requests to a maximum of 5 for message ordering to be preserved.
Ordered delivery with idempotency
# ...
enable.idempotence=true (1)
max.in.flight.requests.per.connection=5 (2)
acks=all (3)
retries=2147483647 (4)
# ...
-
Set to true
to enable the idempotent producer.
-
With idempotent delivery the number of in-flight requests may be greater than 1 while still providing the message ordering guarantee. The default is 5 in-flight requests.
-
Set acks
to all
.
-
Set the number of attempts to resend a failed message request.
If you choose not to use acks=all
and disable idempotency because of the performance cost,
set the number of in-flight (unacknowledged) requests to 1 to preserve ordering.
Otherwise, a situation is possible where Message-A fails only to succeed after Message-B was already written to the broker.
Ordered delivery without idempotency
# ...
enable.idempotence=false (1)
max.in.flight.requests.per.connection=1 (2)
retries=2147483647
# ...
-
Set to false
to disable the idempotent producer.
-
Set the number of in-flight requests to exactly 1
.
Idempotence is useful for exactly once writes to a single partition.
Transactions, when used with idempotence, allow exactly once writes across multiple partitions.
Transactions guarantee that messages using the same transactional ID are produced once,
and either all are successfully written to the respective logs or none of them are.
# ...
enable.idempotence=true
max.in.flight.requests.per.connection=5
acks=all
retries=2147483647
transactional.id=UNIQUE-ID (1)
transaction.timeout.ms=900000 (2)
# ...
-
Specify a unique transactional ID.
-
Set the maximum allowed time for transactions in milliseconds before a timeout error is returned.
The default is 900000
or 15 minutes.
The choice of transactional.id
is important in order that the transactional guarantee is maintained.
Each transactional id should be used for a unique set of topic partitions.
For example, this can be achieved using an external mapping of topic partition names to transactional ids,
or by computing the transactional id from the topic partition names using a function that avoids collisions.
Usually, the requirement of a system is to satisfy a particular throughput target for a proportion of messages within a given latency.
For example, targeting 500,000 messages per second with 95% of messages being acknowledged within 2 seconds.
It’s likely that the messaging semantics (message ordering and durability) of your producer are defined by the requirements for your application.
For instance, it’s possible that you don’t have the option of using acks=0
or acks=1
without breaking some important property or guarantee provided by your application.
Broker restarts have a significant impact on high percentile statistics.
For example, over a long period the 99th percentile latency is dominated by behavior around broker restarts.
This is worth considering when designing benchmarks or comparing performance numbers from benchmarking with performance numbers seen in production.
Depending on your objective, Kafka offers a number of configuration parameters and techniques for tuning producer performance for throughput and latency.
- Message batching (
linger.ms
and batch.size
)
-
Message batching delays sending messages in the hope that more messages destined for the same broker will be sent,
allowing them to be batched into a single produce request.
Batching is a compromise between higher latency in return for higher throughput.
Time-based batching is configured using linger.ms
, and size-based batching is configured using batch.size
.
- Compression (
compression.type
)
-
Message compression adds latency in the producer (CPU time spent compressing the messages),
but makes requests (and potentially disk writes) smaller, which can increase throughput.
Whether compression is worthwhile, and the best compression to use, will depend on the messages being sent.
Compression happens on the thread which calls KafkaProducer.send()
,
so if the latency of this method matters for your application you should consider using more threads.
- Pipelining (
max.in.flight.requests.per.connection
)
-
Pipelining means sending more requests before the response to a previous request has been received.
In general more pipelining means better throughput, up to a threshold at which other effects,
such as worse batching, start to counteract the effect on throughput.
Lowering latency
When your application calls the KafkaProducer.send()
method, messages undergo a series of operations before being sent:
-
Interception: Messages are processed by any configured interceptors.
-
Serialization: Messages are serialized into the appropriate format.
-
Partition assignment: Each message is assigned to a specific partition.
-
Compression: Messages are compressed to conserve network bandwidth.
-
Batching: Compressed messages are added to a batch in a partition-specific queue.
During these operations, the send()
method is momentarily blocked.
It also remains blocked if the buffer.memory
is full or if metadata is unavailable.
Batches will remain in the queue until one of the following occurs:
-
The batch is full (according to batch.size
).
-
The delay introduced by linger.ms
has passed.
-
The sender is ready to dispatch batches for other partitions to the same broker and can include this batch.
-
The producer is being flushed or closed.
To minimize the impact of send()
blocking on latency, optimize batching and buffering configurations.
Use the linger.ms
and batch.size
properties to batch more messages into a single produce request for higher throughput.
# ...
linger.ms=100 (1)
batch.size=16384 (2)
buffer.memory=33554432 (3)
# ...
-
The linger.ms
property adds a delay in milliseconds so that larger batches of messages are accumulated and sent in a request. The default is 0
.
-
If a maximum batch.size
in bytes is used, a request is sent when the maximum is reached, or messages have been queued for longer than linger.ms
(whichever comes sooner).
Adding the delay allows batches to accumulate messages up to the batch size.
-
The buffer size must be at least as big as the batch size, and be able to accommodate buffering, compression, and in-flight requests.
Increasing throughput
You can improve throughput of your message requests by directing messages to a specified partition using a custom partitioner to replace the default.
# ...
partitioner.class=my-custom-partitioner (1)
# ...
-
Specify the class name of your custom partitioner.
Use configuration properties to optimize the performance of Kafka consumers.
When tuning your consumers your primary concern will be ensuring that they cope efficiently with the amount of data ingested.
As with the producer tuning, be prepared to make incremental changes until the consumers operate as expected.
When tuning a consumer, consider the following aspects carefully, as they significantly impact its performance and behavior:
- Scaling
-
Consumer groups enable parallel processing of messages by distributing the load across multiple consumers, enhancing scalability and throughput.
The number of topic partitions determines the maximum level of parallelism that you can achieve, as one partition can only be assigned to one consumer in a consumer group.
- Message ordering
-
If absolute ordering within a topic is important, use a single-partition topic.
A consumer observes messages in a single partition in the same order that they were committed to the broker, which means that Kafka only provides ordering guarantees for messages in a single partition.
It is also possible to maintain message ordering for events specific to individual entities, such as users.
If a new entity is created, you can create a new topic dedicated to that entity.
You can use a unique ID, like a user ID, as the message key and route all messages with the same key to a single partition within the topic.
- Offset reset policy
-
Setting the appropriate offset policy ensures that the consumer consumes messages from the desired starting point and handles message processing accordingly.
The default Kafka reset value is latest
, which starts at the end of the partition, and consequently means some messages might be missed, depending on the consumer’s behavior and the state of the partition.
Setting auto.offset.reset
to earliest
ensures that when connecting with a new group.id
, all messages are retrieved from the beginning of the log.
- Securing access
-
Implement security measures for authentication, encryption, and authorization by setting up user accounts to manage secure access to Kafka.
Connection and deserializer properties are required for every consumer.
Generally, it is good practice to add a client id for tracking.
In a consumer configuration, irrespective of any subsequent configuration:
-
The consumer fetches from a given offset and consumes the messages in order, unless the offset is changed to skip or re-read messages.
-
The broker does not know if the consumer processed the responses, even when committing offsets to Kafka, because the offsets might be sent to a different broker in the cluster.
Basic consumer configuration properties
# ...
bootstrap.servers=localhost:9092 (1)
key.deserializer=org.apache.kafka.common.serialization.StringDeserializer (2)
value.deserializer=org.apache.kafka.common.serialization.StringDeserializer (3)
client.id=my-client (4)
group.id=my-group-id (5)
# ...
-
(Required) Tells the consumer to connect to a Kafka cluster using a host:port bootstrap server address for a Kafka broker.
The consumer uses the address to discover and connect to all brokers in the cluster.
Use a comma-separated list to specify two or three addresses in case a server is down, but it is not necessary to provide a list of all the brokers in the cluster.
If you are using a loadbalancer service to expose the Kafka cluster, you only need the address for the service because the availability is handled by the loadbalancer.
-
(Required) Deserializer to transform the bytes fetched from the Kafka broker into message keys.
-
(Required) Deserializer to transform the bytes fetched from the Kafka broker into message values.
-
(Optional) The logical name for the client, which is used in logs and metrics to identify the source of a request. The id can also be used to throttle consumers based on processing time quotas.
-
(Conditional) A group id is required for a consumer to be able to join a consumer group.
Consumer groups share a typically large data stream generated by one or multiple producers from a given topic.
Consumers are grouped using a group.id
property, allowing messages to be spread across the members.
One of the consumers in the group is elected leader and decides how the partitions are assigned to the consumers in the group.
Each partition can only be assigned to a single consumer.
If you do not already have as many consumers as partitions,
you can scale data consumption by adding more consumer instances with the same group.id
.
Adding more consumers to a group than there are partitions will not help throughput,
but it does mean that there are consumers on standby should one stop functioning.
If you can meet throughput goals with fewer consumers, you save on resources.
Consumers within the same consumer group send offset commits and heartbeats to the same broker.
The consumer sends heartbeats to the Kafka broker to indicate its activity within the consumer group.
So the greater the number of consumers in the group, the higher the request load on the broker.
# ...
group.id=my-group-id (1)
# ...
-
Add a consumer to a consumer group using a group id.
Select an appropriate partition assignment strategy, which determines how Kafka topic partitions are distributed among consumer instances in a group.
Partition strategies are supported by the following classes:
-
org.apache.kafka.clients.consumer.RangeAssignor
-
org.apache.kafka.clients.consumer.RoundRobinAssignor
-
org.apache.kafka.clients.consumer.StickyAssignor
-
org.apache.kafka.clients.consumer.CooperativeStickyAssignor
Specify a class using the partition.assignment.strategy
consumer configuration property.
The range assignment strategy assigns a range of partitions to each consumer, and is useful when you want to process related data together.
Alternatively, opt for a round robin assignment strategy for equal partition distribution among consumers, which is ideal for high-throughput scenarios requiring parallel processing.
For more stable partition assignments, consider the sticky and cooperative sticky strategies.
Sticky strategies aim to maintain assigned partitions during rebalances, when possible.
If a consumer was previously assigned certain partitions, the sticky strategies prioritize retaining those same partitions with the same consumer after a rebalance, while only revoking and reassigning the partitions that are actually moved to another consumer.
Leaving partition assignments in place reduces the overhead on partition movements.
The cooperative sticky strategy also supports cooperative rebalances, enabling uninterrupted consumption from partitions that are not reassigned.
If none of the available strategies suit your data, you can create a custom strategy tailored to your specific requirements.
Kafka brokers receive fetch requests from consumers that ask the broker to send messages from a list of topics, partitions and offset positions.
A consumer observes messages in a single partition in the same order that they were committed to the broker,
which means that Kafka only provides ordering guarantees for messages in a single partition.
Conversely, if a consumer is consuming messages from multiple partitions, the order of messages in different partitions as observed by the consumer does not necessarily reflect the order in which they were sent.
If you want a strict ordering of messages from one topic, use one partition per consumer.
Control the number of messages returned when your client application calls KafkaConsumer.poll()
.
Use the fetch.max.wait.ms
and fetch.min.bytes
properties to increase the minimum amount of data fetched by the consumer from the Kafka broker.
Time-based batching is configured using fetch.max.wait.ms
, and size-based batching is configured using fetch.min.bytes
.
If CPU utilization in the consumer or broker is high, it might be because there are too many requests from the consumer.
You can adjust fetch.max.wait.ms
and fetch.min.bytes
properties higher so that there are fewer requests and messages are delivered in bigger batches.
By adjusting higher, throughput is improved with some cost to latency.
You can also adjust higher if the amount of data being produced is low.
For example, if you set fetch.max.wait.ms
to 500ms and fetch.min.bytes
to 16384 bytes,
when Kafka receives a fetch request from the consumer it will respond when the first of either threshold is reached.
Conversely, you can adjust the fetch.max.wait.ms
and fetch.min.bytes
properties lower to improve end-to-end latency.
# ...
fetch.max.wait.ms=500 (1)
fetch.min.bytes=16384 (2)
# ...
-
The maximum time in milliseconds the broker will wait before completing fetch requests.
The default is 500
milliseconds.
-
If a minimum batch size in bytes is used, a request is sent when the minimum is reached, or messages have been queued for longer than fetch.max.wait.ms
(whichever comes sooner).
Adding the delay allows batches to accumulate messages up to the batch size.
Lowering latency by increasing the fetch request size
Use the fetch.max.bytes
and max.partition.fetch.bytes
properties to increase the maximum amount of data fetched by the consumer from the Kafka broker.
The fetch.max.bytes
property sets a maximum limit in bytes on the amount of data fetched from the broker at one time.
The max.partition.fetch.bytes
sets a maximum limit in bytes on how much data is returned for each partition,
which must always be larger than the number of bytes set in the broker or topic configuration for max.message.bytes
.
The maximum amount of memory a client can consume is calculated approximately as:
NUMBER-OF-BROKERS * fetch.max.bytes and NUMBER-OF-PARTITIONS * max.partition.fetch.bytes
If memory usage can accommodate it, you can increase the values of these two properties.
By allowing more data in each request, latency is improved as there are fewer fetch requests.
# ...
fetch.max.bytes=52428800 (1)
max.partition.fetch.bytes=1048576 (2)
# ...
-
The maximum amount of data in bytes returned for a fetch request.
-
The maximum amount of data in bytes returned for each partition.
The Kafka auto-commit mechanism allows a consumer to commit the offsets of messages automatically.
If enabled, the consumer will commit offsets received from polling the broker at 5000ms intervals.
The auto-commit mechanism is convenient, but it introduces a risk of data loss and duplication.
If a consumer has fetched and transformed a number of messages, but the system crashes with processed messages in the consumer buffer when performing an auto-commit, that data is lost.
If the system crashes after processing the messages, but before performing the auto-commit, the data is duplicated on another consumer instance after rebalancing.
Auto-committing can avoid data loss only when all messages are processed before the next poll to the broker,
or the consumer closes.
To minimize the likelihood of data loss or duplication, you can set enable.auto.commit
to false
and develop your client application to have more control over committing offsets.
Or you can use auto.commit.interval.ms
to decrease the intervals between commits.
# ...
enable.auto.commit=false (1)
# ...
-
Auto commit is set to false to provide more control over committing offsets.
By setting to enable.auto.commit
to false
, you can commit offsets after all processing has been performed and the message has been consumed.
For example, you can set up your application to call the Kafka commitSync
and commitAsync
commit APIs.
The commitSync
API commits the offsets in a message batch returned from polling.
You call the API when you are finished processing all the messages in the batch.
If you use the commitSync
API, the application will not poll for new messages until the last offset in the batch is committed.
If this negatively affects throughput, you can commit less frequently,
or you can use the commitAsync
API.
The commitAsync
API does not wait for the broker to respond to a commit request,
but risks creating more duplicates when rebalancing.
A common approach is to combine both commit APIs in an application, with the commitSync
API used just before shutting the consumer down or rebalancing to make sure the final commit is successful.
Consider using transactional ids and enabling idempotence (enable.idempotence=true
) on the producer side to guarantee exactly-once delivery.
On the consumer side, you can then use the isolation.level
property to control how transactional messages are read by the consumer.
The isolation.level
property has two valid values:
Use read_committed
to ensure that only transactional messages that have been committed are read by the consumer.
However, this will cause an increase in end-to-end latency, because the consumer will not be able to return a message until the brokers have written the transaction markers that record the result of the transaction (committed or aborted).
# ...
enable.auto.commit=false
isolation.level=read_committed (1)
# ...
-
Set to read_committed
so that only committed messages are read by the consumer.
In the event of failures within a consumer group, Kafka provides a rebalance protocol designed for effective detection and recovery.
To minimize the potential impact of these failures, one key strategy is to adjust the max.poll.records
property to balance efficient processing with system stability.
This property determines the maximum number of records a consumer can fetch in a single poll.
Fine-tuning max.poll.records
helps to maintain a controlled consumption rate, preventing the consumer from overwhelming itself or the Kafka broker.
Additionally, Kafka offers advanced configuration properties like session.timeout.ms
and heartbeat.interval.ms
.
These settings are typically reserved for more specialized use cases and may not require adjustment in standard scenarios.
The session.timeout.ms
property specifies the maximum amount of time a consumer can go without sending a heartbeat to the Kafka broker to indicate it is active within the consumer group.
If a consumer fails to send a heartbeat within the session timeout, it is considered inactive.
A consumer marked as inactive triggers a rebalancing of the partitions for the topic.
Setting the session.timeout.ms
property value too low can result in false-positive outcomes, while setting it too high can lead to delayed recovery from failures.
The heartbeat.interval.ms
property determines how frequently a consumer sends heartbeats to the Kafka broker.
A shorter interval between consecutive heartbeats allows for quicker detection of consumer failures.
The heartbeat interval must be lower, usually by a third, than the session timeout.
Decreasing the heartbeat interval reduces the chance of accidental rebalancing, but more frequent heartbeats increases the overhead on broker resources.
# ...
max.poll.records=100 # (1)
session.timeout.ms=30000 # (2)
heartbeat.interval.ms=5000 # (3)
# ...
-
Set the number records returned to the consumer when calling the poll()
method.
-
Set the timeout for detecting client failure.
If the broker configuration has a group.min.session.timeout.ms
and group.max.session.timeout.ms
, the session timeout value must be within that range.
-
Adjust the heartbeat interval according to anticipated rebalances.
Use the auto.offset.reset
property to control how a consumer behaves when no offsets have been committed,
or a committed offset is no longer valid or deleted.
Suppose you deploy a consumer application for the first time, and it reads messages from an existing topic.
Because this is the first time the group.id
is used, the __consumer_offsets
topic does not contain any offset information for this application.
The new application can start processing all existing messages from the start of the log or only new messages.
The default reset value is latest
, which starts at the end of the partition, and consequently means some messages are missed.
To avoid data loss, but increase the amount of processing, set auto.offset.reset
to earliest
to start at the beginning of the partition.
Also consider using the earliest
option to avoid messages being lost when the offsets retention period (offsets.retention.minutes
) configured for a broker has ended.
If a consumer group or standalone consumer is inactive and commits no offsets during the retention period, previously committed offsets are deleted from __consumer_offsets
.
# ...
auto.offset.reset=earliest # (1)
# ...
-
Set to earliest
to return to the start of a partition and avoid data loss if offsets were not committed.
If the amount of data returned in a single fetch request is large,
a timeout might occur before the consumer has processed it.
In this case, you can lower max.partition.fetch.bytes
or increase session.timeout.ms
.
Rebalances in Kafka consumer groups can introduce latency and reduce throughput, impacting overall service performance.
The rebalancing of a partition between active consumers in a group is the time it takes for the following to take place:
-
Consumers to commit their offsets
-
The new consumer group to be formed
-
The group leader to assign partitions to group members
-
The consumers in the group to receive their assignments and start fetching
Rebalances are triggered by changes in consumer health, network issues, configuration updates, and scaling events.
This process can increase service downtime, especially if it occurs frequently, such as during rolling restarts of consumers in a group.
To minimize the impact of rebalances, consider the following strategies and configurations:
- Assess throughput and parallelism
-
Assess the expected throughput (bytes and records per second) and parallelism (number of partitions) of the input topics against the number of consumers.
If adjustments are needed, start by setting up static membership, adopting a partition assignment strategy, and setting a limit on the number of records returned using the max.poll.records
property.
Add further configurations for timeouts and intervals, if required and with care, as these can introduce issues related to the handling of failures.
- Use static membership
-
Assign a unique identifier (group.instance.id
) to each consumer instance.
Static membership introduces persistence so static consumers retain partition assignments across restarts, reducing unnecessary rebalances.
- Adopt partition assignment strategies
-
-
Use appropriate partition assignment strategies to reduce the number of partitions that need to be reassigned during a rebalance, minimizing the impact on active consumers.
-
The org.apache.kafka.clients.consumer.CooperativeStickyAssignor
strategy is particularly effective, as it ensures minimal partition movement and better stability during rebalances.
- Adjust record limits and poll intervals
-
-
Use the max.poll.records
property to limit the number of records returned during each poll.
Processing fewer messages more efficiently can prevent delays.
-
Use the max.poll.interval.ms
property to prevent rebalances caused by prolonged processing tasks by setting the maximum interval between calls to the poll()
method.
-
Alternatively, consider pausing partitions to retrieve fewer records at a time.
- Adjust session timeout and heartbeat intervals
-
-
Use the session.timeout.ms
property to set a longer timeout to reduce rebalances caused by temporary network glitches or minor processing delays.
-
Adjust the heartbeat.interval.ms
property to balance failure detection checks with minimizing unnecessary rebalances.
- Monitor consumer health
-
Instability in consumer applications, such as frequent crashes, can trigger rebalances.
Use Kafka consumer metrics to monitor such things as rebalance rates, session timouts, and failed fetch requests.
Example configuration to minimize the impact of rebalances
# ...
group.instance.id=<unique_id>
max.poll.interval.ms=300000
max.poll.records=500
session.timeout.ms=30000
heartbeat.interval.ms=5000
partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# ...
Scaling strategies
To minimize the impact of rebalances during scaling of consumer groups, consider the following approaches:
- Set a rebalance delay
-
Use the group.initial.rebalance.delay.ms
property in the Kafka configuration to delay the time it takes for consumers to join a new consumer group before performing a rebalance.
Introducing a delay helps avoid triggering several rebalances when starting multiple consumers near the same time.
The appropriate delay depends on the orchestration used and might not be suitable in some circumstances.
- Avoid frequent scaling
-
-
Keep the number of consumers stable, scaling only when necessary and in controlled increments.
-
Monitor system performance and adjust your scaling strategy as needed.
-
Use the Kafka Exporter to check for consumer lag and determine if scaling is required.
- Implement dynamic scaling policies
-
-
If using dynamic or event-driven tools for scaling of consumer applications, set lag thresholds based on the backlog of messages.
-
Define maximum and minimum replica counts for consumer groups.
-
Set periods between scaling events to prevent rapid scaling.
Note
|
In cases where lengthy message processing is unavoidable, consider pausing and resuming partitions as needed.
If you pause all partitions, poll() returns no records, allowing you to keep calling it without overwhelming the consumers.
Alternatively, you can offload the processing tasks to a pool of worker threads.
This helps prevents delays and potential rebalances.
|
If your Strimzi deployment needs to handle a high volume of messages, you can use configuration options to optimize for throughput and latency.
Producer and consumer configuration can help control the size and frequency of requests to Kafka brokers.
For more information on the configuration options, see the following:
You can also use the same configuration options with the producers and consumers used by the Kafka Connect runtime source connectors (including MirrorMaker 2) and sink connectors.
- Source connectors
-
-
Producers from the Kafka Connect runtime send messages to the Kafka cluster.
-
For MirrorMaker 2, since the source system is Kafka, consumers retrieve messages from a source Kafka cluster.
- Sink connectors
-
For consumers, you might increase the amount of data fetched in a single fetch request to reduce latency.
You increase the fetch request size using the fetch.max.bytes
and max.partition.fetch.bytes
properties.
You can also set a maximum limit on the number of messages returned from the consumer buffer using the max.poll.records
property.
For MirrorMaker 2, configure the fetch.max.bytes
, max.partition.fetch.bytes
, and max.poll.records
values at the source connector level (consumer.*
), as they relate to the specific consumer that fetches messages from the source.
For producers, you might increase the size of the message batches sent in a single produce request.
You increase the batch size using the batch.size
property.
A larger batch size reduces the number of outstanding messages ready to be sent and the size of the backlog in the message queue.
Messages being sent to the same partition are batched together.
A produce request is sent to the target cluster when the batch size is reached.
By increasing the batch size, produce requests are delayed and more messages are added to the batch and sent to brokers at the same time.
This can improve throughput when you have just a few topic partitions that handle large numbers of messages.
Consider the number and size of the records that the producer handles for a suitable producer batch size.
Use linger.ms
to add a wait time in milliseconds to delay produce requests when producer load decreases.
The delay means that more records can be added to batches if they are under the maximum batch size.
Configure the batch.size
and linger.ms
values at the source connector level (producer.override.*
), as they relate to the specific producer that sends messages to the target Kafka cluster.
For Kafka Connect source connectors, the data streaming pipeline to the target Kafka cluster is as follows:
Data streaming pipeline for Kafka Connect source connector
external data source → (Kafka Connect tasks) source message queue → producer buffer → target Kafka topic
For Kafka Connect sink connectors, the data streaming pipeline to the target external data source is as follows:
Data streaming pipeline for Kafka Connect sink connector
source Kafka topic → (Kafka Connect tasks) sink message queue → consumer buffer → external data source
For MirrorMaker 2, the data mirroring pipeline to the target Kafka cluster is as follows:
Data mirroring pipeline for MirrorMaker 2
source Kafka topic → (Kafka Connect tasks) source message queue → producer buffer → target Kafka topic
The producer sends messages in its buffer to topics in the target Kafka cluster.
While this is happening, Kafka Connect tasks continue to poll the data source to add messages to the source message queue.
The size of the producer buffer for the source connector is set using the producer.override.buffer.memory
property.
Tasks wait for a specified timeout period (offset.flush.timeout.ms
) before the buffer is flushed.
This should be enough time for the sent messages to be acknowledged by the brokers and offset data committed.
The source task does not wait for the producer to empty the message queue before committing offsets, except during shutdown.
If the producer is unable to keep up with the throughput of messages in the source message queue, buffering is blocked until there is space available in the buffer within a time period bounded by max.block.ms
.
Any unacknowledged messages still in the buffer are sent during this period.
New messages are not added to the buffer until these messages are acknowledged and flushed.
You can try the following configuration changes to keep the underlying source message queue of outstanding messages at a manageable size:
-
Increasing the default value in milliseconds of the offset.flush.timeout.ms
-
Ensuring that there are enough CPU and memory resources
-
Increasing the number of tasks that run in parallel by doing the following:
Consider the number of tasks that can run in parallel according to the available CPU and memory resources and number of worker nodes.
You might need to keep adjusting the configuration values until they have the desired effect.
Kafka Connect fetches data from the source external data system and hands it to the Kafka Connect runtime producers so that it’s replicated to the target cluster.
The following example shows configuration for Kafka Connect using the KafkaConnect
custom resource.
Example Kafka Connect configuration for handling high volumes of messages
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnect
metadata:
name: my-connect-cluster
annotations:
strimzi.io/use-connector-resources: "true"
spec:
replicas: 3
config:
offset.flush.timeout.ms: 10000
# ...
resources:
requests:
cpu: "1"
memory: 2Gi
limits:
cpu: "2"
memory: 2Gi
# ...
Producer configuration is added for the source connector, which is managed using the KafkaConnector
custom resource.
Example source connector configuration for handling high volumes of messages
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: org.apache.kafka.connect.file.FileStreamSourceConnector
tasksMax: 2
config:
producer.override.batch.size: 327680
producer.override.linger.ms: 100
# ...
Note
|
FileStreamSourceConnector and FileStreamSinkConnector are provided as example connectors.
For information on deploying them as KafkaConnector resources, see Deploying KafkaConnector resources.
|
Consumer configuration is added for the sink connector.
Example sink connector configuration for handling high volumes of messages
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-sink-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
class: org.apache.kafka.connect.file.FileStreamSinkConnector
tasksMax: 2
config:
consumer.fetch.max.bytes: 52428800
consumer.max.partition.fetch.bytes: 1048576
consumer.max.poll.records: 500
# ...
If you are using the Kafka Connect API instead of the KafkaConnector
custom resource to manage your connectors, you can add the connector configuration as a JSON object.
Example curl request to add source connector configuration for handling high volumes of messages
curl -X POST \
http://my-connect-cluster-connect-api:8083/connectors \
-H 'Content-Type: application/json' \
-d '{ "name": "my-source-connector",
"config":
{
"connector.class":"org.apache.kafka.connect.file.FileStreamSourceConnector",
"file": "/opt/kafka/LICENSE",
"topic":"my-topic",
"tasksMax": "4",
"type": "source"
"producer.override.batch.size": 327680
"producer.override.linger.ms": 100
}
}'
MirrorMaker 2 fetches data from the source cluster and hands it to the Kafka Connect runtime producers so that it’s replicated to the target cluster.
The following example shows the configuration for MirrorMaker 2 using the KafkaMirrorMaker2
custom resource.
Example MirrorMaker 2 configuration for handling high volumes of messages
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
version: 3.8.0
replicas: 1
connectCluster: "my-cluster-target"
clusters:
- alias: "my-cluster-source"
bootstrapServers: my-cluster-source-kafka-bootstrap:9092
- alias: "my-cluster-target"
config:
offset.flush.timeout.ms: 10000
bootstrapServers: my-cluster-target-kafka-bootstrap:9092
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 2
config:
producer.override.batch.size: 327680
producer.override.linger.ms: 100
consumer.fetch.max.bytes: 52428800
consumer.max.partition.fetch.bytes: 1048576
consumer.max.poll.records: 500
# ...
resources:
requests:
cpu: "1"
memory: Gi
limits:
cpu: "2"
memory: 4Gi
If you are using Prometheus and Grafana to monitor your deployment, you can check the MirrorMaker 2 message flow.
The example MirrorMaker 2 Grafana dashboards provided with Strimzi show the following metrics related to the flush pipeline.
-
The number of messages in Kafka Connect’s outstanding messages queue
-
The available bytes of the producer buffer
-
The offset commit timeout in milliseconds
You can use these metrics to gauge whether or not you need to tune your configuration based on the volume of messages.
Kafka’s default batch size for messages is 1MB, which is optimal for maximum throughput in most use cases.
Kafka can accommodate larger batches at a reduced throughput, assuming adequate disk capacity.
Large message sizes can be handled in four ways:
-
Brokers, producers, and consumers are configured to accommodate larger message sizes.
-
Producer-side message compression writes compressed messages to the log.
-
Reference-based messaging sends only a reference to data stored in some other system in the message’s payload.
-
Inline messaging splits messages into chunks that use the same key, which are then combined on output using a stream-processor like Kafka Streams.
Unless you are handling very large messages, the configuration approach is recommended.
The reference-based messaging and message compression options cover most other situations.
With any of these options, care must be taken to avoid introducing performance issues.
Large messages can impact system performance and introduce complexities in message processing.
If they cannot be avoided, there are configuration options available.
To handle larger messages efficiently and prevent blocks in the message flow, consider adjusting the following configurations:
-
Adjusting the maximum record batch size:
-
Increasing the maximum size of messages fetched by each partition follower (replica.fetch.max.bytes
).
-
Increasing the batch size (batch.size
) for producers to increase the size of message batches sent in a single produce request.
-
Configuring a higher maximum request size for producers (max.request.size
) and consumers (fetch.max.bytes
) to accommodate larger record batches.
-
Setting a higher maximum limit (max.partition.fetch.bytes
) on how much data is returned to consumers for each partition.
Ensure that the maximum size for batch requests is at least as large as message.max.bytes
to accommodate the largest record batch size.
Example broker configuration
message.max.bytes: 10000000
replica.fetch.max.bytes: 10485760
Example producer configuration
batch.size: 327680
max.request.size: 10000000
Example consumer configuration
fetch.max.bytes: 10000000
max.partition.fetch.bytes: 10485760
It’s also possible to configure the producers and consumers used by other Kafka components like Kafka Bridge, Kafka Connect, and MirrorMaker 2 to handle larger messages more effectively.
- Kafka Bridge
-
Configure the Kafka Bridge using specific producer and consumer configuration properties:
Example Kafka Bridge configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
name: my-bridge
spec:
# ...
producer:
config:
batch.size: 327680
max.request.size: 10000000
consumer:
config:
fetch.max.bytes: 10000000
max.partition.fetch.bytes: 10485760
# ...
- Kafka Connect
-
For Kafka Connect, configure the source and sink connectors responsible for sending and retrieving messages using prefixes for producer and consumer configuration properties:
Example Kafka Connect source connector configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-source-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
# ...
config:
producer.override.batch.size: 327680
producer.override.max.request.size: 10000000
# ...
Example Kafka Connect sink connector configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaConnector
metadata:
name: my-sink-connector
labels:
strimzi.io/cluster: my-connect-cluster
spec:
# ...
config:
consumer.fetch.max.bytes: 10000000
consumer.max.partition.fetch.bytes: 10485760
# ...
- MirrorMaker 2
-
For MirrorMaker 2, configure the source connector responsible for retrieving messages from the source Kafka cluster using prefixes for producer and consumer configuration properties:
-
producer.override
for the runtime Kafka Connect producer used to replicate data to the target Kafka cluster
-
consumer
for the consumer used by the sink connector to retrieve messages from the source Kafka cluster
Example MirrorMaker 2 source connector configuration
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaMirrorMaker2
metadata:
name: my-mirror-maker2
spec:
# ...
mirrors:
- sourceCluster: "my-cluster-source"
targetCluster: "my-cluster-target"
sourceConnector:
tasksMax: 2
config:
producer.override.batch.size: 327680
producer.override.max.request.size: 10000000
consumer.fetch.max.bytes: 10000000
consumer.max.partition.fetch.bytes: 10485760
# ...
For producer configuration, you specify a compression.type
, such as Gzip, which is then applied to batches of data generated by the producer.
Using the broker configuration compression.type=producer
(default), the broker retains whatever compression the producer used.
Whenever producer and topic compression do not match, the broker has to compress batches again prior to appending them to the log, which impacts broker performance.
Compression also adds additional processing overhead on the producer and decompression overhead on the consumer,
but includes more data in a batch, so is often beneficial to throughput when message data compresses well.
Combine producer-side compression with fine-tuning of the batch size to facilitate optimum throughput.
Using metrics helps to gauge the average batch size needed.
Reference-based messaging is useful for data replication when you do not know how big a message will be.
The external data store must be fast, durable, and highly available for this configuration to work.
Data is written to the data store and a reference to the data is returned.
The producer sends a message containing the reference to Kafka.
The consumer gets the reference from the message and uses it to fetch the data from the data store.
As the message passing requires more trips, end-to-end latency will increase.
Another significant drawback of this approach is there is no automatic clean up of the data in the external system when the Kafka message gets cleaned up.
A hybrid approach would be to only send large messages to the data store and process standard-sized messages directly.
Inline messaging
Inline messaging is complex, but it does not have the overhead of depending on external systems like reference-based messaging.
The producing client application has to serialize and then chunk the data if the message is too big.
The producer then uses the Kafka ByteArraySerializer
or similar to serialize each chunk again before sending it.
The consumer tracks messages and buffers chunks until it has a complete message.
The consuming client application receives the chunks, which are assembled before deserialization.
Complete messages are delivered to the rest of the consuming application in order according to the offset of the first or last chunk for each set of chunked messages.
The consumer should commit its offset only after receiving and processing all message chunks to ensure accurate tracking of message delivery and prevent duplicates during rebalancing.
Chunks might be spread across segments.
Consumer-side handling should cover the possibility that a chunk becomes unavailable if a segment is subsequently deleted.
Figure 11. Inline messaging flow
Inline messaging has a performance overhead on the consumer side because of the buffering required, particularly when handling a series of large messages in parallel.
The chunks of large messages can become interleaved, so that it is not always possible to commit when all the chunks of a message have been consumed if the chunks of another large message in the buffer are incomplete.
For this reason, the buffering is usually supported by persisting message chunks or by implementing commit logic.