Skip to content
Home » [NEW] Apache Kafka | persistence คือ – NATAVIGUIDES

[NEW] Apache Kafka | persistence คือ – NATAVIGUIDES

persistence คือ: นี่คือโพสต์ที่เกี่ยวข้องกับหัวข้อนี้

Table of Contents

Documentation

Kafka 3.0 Documentation

Prior releases: 0.8.0,
0.8.1.X,
0.8.2.X,
0.9.0.X,
0.10.0.X,
0.10.1.X,
0.10.2.X,
0.11.0.X,
1.0.X,
1.1.X,
2.0.X,
2.1.X,
2.2.X,
2.3.X,
2.4.X,
2.5.X,
2.6.X,
2.7.X,
2.8.X.

Prior releases: 0.7.x

Here is a description of a few of the popular use cases for Apache Kafka®.
For an overview of a number of these areas in action, see this blog post.

Kafka works well as a replacement for a more traditional message broker.
Message brokers are used for a variety of reasons (to decouple processing from data producers, to buffer unprocessed messages, etc).
In comparison to most messaging systems Kafka has better throughput, built-in partitioning, replication, and fault-tolerance which makes it a good
solution for large scale message processing applications.

Kafka works well as a replacement for a more traditional message broker. Message brokers are used for a variety of reasons (to decouple processing from data producers, to buffer unprocessed messages, etc). In comparison to most messaging systems Kafka has better throughput, built-in partitioning, replication, and fault-tolerance which makes it a good solution for large scale message processing applications.

In our experience messaging uses are often comparatively low-throughput, but may require low end-to-end latency and often depend on the strong
durability guarantees Kafka provides.

In this domain Kafka is comparable to traditional messaging systems such as ActiveMQ or
RabbitMQ.

The original use case for Kafka was to be able to rebuild a user activity tracking pipeline as a set of real-time publish-subscribe feeds.
This means site activity (page views, searches, or other actions users may take) is published to central topics with one topic per activity type.
These feeds are available for subscription for a range of use cases including real-time processing, real-time monitoring, and loading into Hadoop or
offline data warehousing systems for offline processing and reporting.

The original use case for Kafka was to be able to rebuild a user activity tracking pipeline as a set of real-time publish-subscribe feeds. This means site activity (page views, searches, or other actions users may take) is published to central topics with one topic per activity type. These feeds are available for subscription for a range of use cases including real-time processing, real-time monitoring, and loading into Hadoop or offline data warehousing systems for offline processing and reporting.

Activity tracking is often very high volume as many activity messages are generated for each user page view.

Kafka is often used for operational monitoring data.
This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.

Many people use Kafka as a replacement for a log aggregation solution.
Log aggregation typically collects physical log files off servers and puts them in a central place (a file server or HDFS perhaps) for processing.
Kafka abstracts away the details of files and gives a cleaner abstraction of log or event data as a stream of messages.
This allows for lower-latency processing and easier support for multiple data sources and distributed data consumption.

In comparison to log-centric systems like Scribe or Flume, Kafka offers equally good performance, stronger durability guarantees due to replication,
and much lower end-to-end latency.

Many users of Kafka process data in processing pipelines consisting of multiple stages, where raw input data is consumed from Kafka topics and then
aggregated, enriched, or otherwise transformed into new topics for further consumption or follow-up processing.
For example, a processing pipeline for recommending news articles might crawl article content from RSS feeds and publish it to an “articles” topic;
further processing might normalize or deduplicate this content and publish the cleansed article content to a new topic;
a final processing stage might attempt to recommend this content to users.
Such processing pipelines create graphs of real-time data flows based on the individual topics.
Starting in 0.10.0.0, a light-weight but powerful stream processing library called

Kafka can serve as a kind of external commit-log for a distributed system. The log helps replicate data between nodes and acts as a re-syncing
mechanism for failed nodes to restore their data.
The

There are a plethora of tools that integrate with Kafka outside the main distribution. The

Here is some information on actually running Kafka as a production system based on usage and experience at LinkedIn. Please send us any additional tips you know of.

This section will review the most common operations you will perform on your Kafka cluster. All of the tools reviewed in this section are available under the bin/ directory of the Kafka distribution and each tool will print details on all possible commandline options if it is run with no arguments.

You have the option of either adding topics manually or having them be created automatically when data is first published to a non-existent topic. If topics are auto-created then you may want to tune the default

Kafka is often used for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.Many people use Kafka as a replacement for a log aggregation solution. Log aggregation typically collects physical log files off servers and puts them in a central place (a file server or HDFS perhaps) for processing. Kafka abstracts away the details of files and gives a cleaner abstraction of log or event data as a stream of messages. This allows for lower-latency processing and easier support for multiple data sources and distributed data consumption. In comparison to log-centric systems like Scribe or Flume, Kafka offers equally good performance, stronger durability guarantees due to replication, and much lower end-to-end latency.Many users of Kafka process data in processing pipelines consisting of multiple stages, where raw input data is consumed from Kafka topics and then aggregated, enriched, or otherwise transformed into new topics for further consumption or follow-up processing. For example, a processing pipeline for recommending news articles might crawl article content from RSS feeds and publish it to an “articles” topic; further processing might normalize or deduplicate this content and publish the cleansed article content to a new topic; a final processing stage might attempt to recommend this content to users. Such processing pipelines create graphs of real-time data flows based on the individual topics. Starting in 0.10.0.0, a light-weight but powerful stream processing library called Kafka Streams is available in Apache Kafka to perform such data processing as described above. Apart from Kafka Streams, alternative open source stream processing tools include Apache Storm and Apache Samza Event sourcing is a style of application design where state changes are logged as a time-ordered sequence of records. Kafka’s support for very large stored log data makes it an excellent backend for an application built in this style.Kafka can serve as a kind of external commit-log for a distributed system. The log helps replicate data between nodes and acts as a re-syncing mechanism for failed nodes to restore their data. The log compaction feature in Kafka helps support this usage. In this usage Kafka is similar to Apache BookKeeper project.There are a plethora of tools that integrate with Kafka outside the main distribution. The ecosystem page lists many of these, including stream processing systems, Hadoop integration, monitoring, and deployment tools.Here is some information on actually running Kafka as a production system based on usage and experience at LinkedIn. Please send us any additional tips you know of.This section will review the most common operations you will perform on your Kafka cluster. All of the tools reviewed in this section are available under thedirectory of the Kafka distribution and each tool will print details on all possible commandline options if it is run with no arguments.You have the option of either adding topics manually or having them be created automatically when data is first published to a non-existent topic. If topics are auto-created then you may want to tune the default topic configurations used for auto-created topics.

Topics are added and modified using the topic tool:

  > bin/kafka-topics.sh --bootstrap-server broker_host:port --create --topic my_topic_name \
        --partitions 20 --replication-factor 3 --config x=y

The replication factor controls how many servers will replicate each message that is written. If you have a replication factor of 3 then up to 2 servers can fail before you will lose access to your data. We recommend you use a replication factor of 2 or 3 so that you can transparently bounce machines without interrupting data consumption.

The replication factor controls how many servers will replicate each message that is written. If you have a replication factor of 3 then up to 2 servers can fail before you will lose access to your data. We recommend you use a replication factor of 2 or 3 so that you can transparently bounce machines without interrupting data consumption.

The partition count controls how many logs the topic will be sharded into. There are several impacts of the partition count. First each partition must fit entirely on a single server. So if you have 20 partitions the full data set (and read and write load) will be handled by no more than 20 servers (not counting replicas). Finally the partition count impacts the maximum parallelism of your consumers. This is discussed in greater detail in the concepts section.

Each sharded partition log is placed into its own folder under the Kafka log directory. The name of such folders consists of the topic name, appended by a dash (-) and the partition id. Since a typical folder name can not be over 255 characters long, there will be a limitation on the length of topic names. We assume the number of partitions will not ever be above 100,000. Therefore, topic names cannot be longer than 249 characters. This leaves just enough room in the folder name for a dash and a potentially 5 digit long partition id.

The configurations added on the command line override the default settings the server has for things like the length of time data should be retained. The complete set of per-topic configurations is documented here.

You can change the configuration or partitioning of a topic using the same topic tool.

You can change the configuration or partitioning of a topic using the same topic tool.

To add partitions you can do

  > bin/kafka-topics.sh --bootstrap-server broker_host:port --alter --topic my_topic_name \
        --partitions 40

Be aware that one use case for partitions is to semantically partition data, and adding partitions doesn’t change the partitioning of existing data so this may disturb consumers if they rely on that partition. That is if data is partitioned by hash(key) % number_of_partitions then this partitioning will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way.

Be aware that one use case for partitions is to semantically partition data, and adding partitions doesn’t change the partitioning of existing data so this may disturb consumers if they rely on that partition. That is if data is partitioned bythen this partitioning will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way.

To add configs:

  > bin/kafka-configs.sh --bootstrap-server broker_host:port --entity-type topics --entity-name my_topic_name --alter --add-config x=y

To remove a config:

  > bin/kafka-configs.sh --bootstrap-server broker_host:port --entity-type topics --entity-name my_topic_name --alter --delete-config x

And finally deleting a topic:

  > bin/kafka-topics.sh --bootstrap-server broker_host:port --delete --topic my_topic_name

To remove a config:And finally deleting a topic:

Kafka does not currently support reducing the number of partitions for a topic.

Instructions for changing the replication factor of a topic can be found here.

The Kafka cluster will automatically detect any broker shutdown or failure and elect new leaders for the partitions on that machine. This will occur whether a server fails or it is brought down intentionally for maintenance or configuration changes. For the latter cases Kafka supports a more graceful mechanism for stopping a server than just killing it.

When a server is stopped gracefully it has two optimizations it will take advantage of:

  1. It will sync all its logs to disk to avoid needing to do any log recovery when it restarts (i.e. validating the checksum for all messages in the tail of the log). Log recovery takes time so this speeds up intentional restarts.
  2. It will migrate any partitions the server is the leader for to other replicas prior to shutting down. This will make the leadership transfer faster and minimize the time each partition is unavailable to a few milliseconds.

Syncing the logs will happen automatically whenever the server is stopped other than by a hard kill, but the controlled leadership migration requires using a special setting:

      controlled.shutdown.enable=true

Note that controlled shutdown will only succeed if the partitions hosted on the broker have replicas (i.e. the replication factor is greater than 1 at least one of these replicas is alive). This is generally what you want since shutting down the last replica would make that topic partition unavailable.

Whenever a broker stops or crashes, leadership for that broker’s partitions transfers to other replicas. When the broker is restarted it will only be a follower for all its partitions, meaning it will not be used for client reads and writes.

The Kafka cluster will automatically detect any broker shutdown or failure and elect new leaders for the partitions on that machine. This will occur whether a server fails or it is brought down intentionally for maintenance or configuration changes. For the latter cases Kafka supports a more graceful mechanism for stopping a server than just killing it. When a server is stopped gracefully it has two optimizations it will take advantage of:Syncing the logs will happen automatically whenever the server is stopped other than by a hard kill, but the controlled leadership migration requires using a special setting:Note that controlled shutdown will only succeed ifthe partitions hosted on the broker have replicas (i.e. the replication factor is greater than 1at least one of these replicas is alive). This is generally what you want since shutting down the last replica would make that topic partition unavailable.Whenever a broker stops or crashes, leadership for that broker’s partitions transfers to other replicas. When the broker is restarted it will only be a follower for all its partitions, meaning it will not be used for client reads and writes.

To avoid this imbalance, Kafka has a notion of preferred replicas. If the list of replicas for a partition is 1,5,9 then node 1 is preferred as the leader to either node 5 or 9 because it is earlier in the replica list. By default the Kafka cluster will try to restore leadership to the preferred replicas. This behaviour is configured with:

      auto.leader.rebalance.enable=true

You can also set this to false, but you will then need to manually restore leadership to the restored replicas by running the command:

  > bin/kafka-preferred-replica-election.sh --bootstrap-server broker_host:port

The rack awareness feature spreads replicas of the same partition across different racks. This extends the guarantees Kafka provides for broker-failure to cover rack-failure, limiting the risk of data loss should all the brokers on a rack fail at once. The feature can also be applied to other broker groupings such as availability zones in EC2.

You can also set this to false, but you will then need to manually restore leadership to the restored replicas by running the command:The rack awareness feature spreads replicas of the same partition across different racks. This extends the guarantees Kafka provides for broker-failure to cover rack-failure, limiting the risk of data loss should all the brokers on a rack fail at once. The feature can also be applied to other broker groupings such as availability zones in EC2.

You can specify that a broker belongs to a particular rack by adding a property to the broker config:

  broker.rack=my-rack-id

When a topic is

You can specify that a broker belongs to a particular rack by adding a property to the broker config:When a topic is created modified or replicas are redistributed , the rack constraint will be honoured, ensuring replicas span as many racks as they can (a partition will span min(#racks, replication-factor) different racks).

The algorithm used to assign replicas to brokers ensures that the number of leaders per broker will be constant, regardless of how brokers are distributed across racks. This ensures balanced throughput.

The algorithm used to assign replicas to brokers ensures that the number of leaders per broker will be constant, regardless of how brokers are distributed across racks. This ensures balanced throughput.

However if racks are assigned different numbers of brokers, the assignment of replicas will not be even. Racks with fewer brokers will get more replicas, meaning they will use more storage and put more resources into replication. Hence it is sensible to configure an equal number of brokers per rack.

However if racks are assigned different numbers of brokers, the assignment of replicas will not be even. Racks with fewer brokers will get more replicas, meaning they will use more storage and put more resources into replication. Hence it is sensible to configure an equal number of brokers per rack.

Kafka administrators can define data flows that cross the boundaries of individual Kafka clusters, data centers, or geographical regions. Please refer to the section on Geo-Replication for further information.

Sometimes it’s useful to see the position of your consumers. We have a tool that will show the position of all consumers in a consumer group as well as how far behind the end of the log they are. To run this tool on a consumer group named consuming a topic named would look like this:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group

  TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST                           CLIENT-ID
  my-topic                       0          2               4               2          consumer-1-029af89c-873c-4751-a720-cefd41a669d6   /127.0.0.1                     consumer-1
  my-topic                       1          2               3               1          consumer-1-029af89c-873c-4751-a720-cefd41a669d6   /127.0.0.1                     consumer-1
  my-topic                       2          2               3               1          consumer-2-42c1abd4-e3b2-425d-a8bb-e1ea49b29bb2   /127.0.0.1                     consumer-2

With the ConsumerGroupCommand tool, we can list, describe, or delete the consumer groups. The consumer group can be deleted manually, or automatically when the last committed offset for that group expires. Manual deletion works only if the group does not have any active members.

For example, to list all consumer groups across all topics:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list

  test-consumer-group

To view offsets, as mentioned earlier, we “describe” the consumer group like this:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group

  TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                    HOST            CLIENT-ID
  topic3          0          241019          395308          154289          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic2          1          520678          803288          282610          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic3          1          241018          398817          157799          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic1          0          854144          855809          1665            consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1
  topic2          0          460537          803290          342753          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1
  topic3          2          243655          398812          155157          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4

There are a number of additional “describe” options that can be used to provide more detailed information about a consumer group:

  • –members: This option provides the list of all active members in the consumer group.
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --members
    
          CONSUMER-ID                                    HOST            CLIENT-ID       #PARTITIONS
          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1       2
          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4       1
          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2       3
          consumer3-ecea43e4-1f01-479f-8349-f9130b75d8ee /127.0.0.1      consumer3       0
  • –members –verbose: On top of the information reported by the “–members” options above, this option also provides the partitions assigned to each member.
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --members --verbose
    
          CONSUMER-ID                                    HOST            CLIENT-ID       #PARTITIONS     ASSIGNMENT
          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1       2               topic1(0), topic2(0)
          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4       1               topic3(2)
          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2       3               topic2(1), topic3(0,1)
          consumer3-ecea43e4-1f01-479f-8349-f9130b75d8ee /127.0.0.1      consumer3       0               -
  • –offsets: This is the default describe option and provides the same output as the “–describe” option.
  • –state: This option provides useful group-level information.
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --state
    
          COORDINATOR (ID)          ASSIGNMENT-STRATEGY       STATE                #MEMBERS
          localhost:9092 (0)        range                     Stable               4

To manually delete one or multiple consumer groups, the “–delete” option can be used:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --delete --group my-group --group my-other-group

  Deletion of requested consumer groups ('my-group', 'my-other-group') was successful.

Sometimes it’s useful to see the position of your consumers. We have a tool that will show the position of all consumers in a consumer group as well as how far behind the end of the log they are. To run this tool on a consumer group namedconsuming a topic namedwould look like this:With the ConsumerGroupCommand tool, we can list, describe, or delete the consumer groups. The consumer group can be deleted manually, or automatically when the last committed offset for that group expires. Manual deletion works only if the group does not have any active members. For example, to list all consumer groups across all topics:To view offsets, as mentioned earlier, we “describe” the consumer group like this:There are a number of additional “describe” options that can be used to provide more detailed information about a consumer group:To manually delete one or multiple consumer groups, the “–delete” option can be used:

To reset offsets of a consumer group, “–reset-offsets” option can be used.
This option supports one consumer group at the time. It requires defining following scopes: –all-topics or –topic. One scope must be selected, unless you use ‘–from-file’ scenario. Also, first make sure that the consumer instances are inactive.
See KIP-122 for more details.

It has 3 execution options:

  • (default) to display which offsets to reset.
  • –execute : to execute –reset-offsets process.
  • –export : to export the results to a CSV format.

–reset-offsets also has following scenarios to choose from (at least one scenario must be selected):

  • –to-datetime <String: datetime> : Reset offsets to offsets from datetime. Format: ‘YYYY-MM-DDTHH:mm:SS.sss’
  • –to-earliest : Reset offsets to earliest offset.
  • –to-latest : Reset offsets to latest offset.
  • –shift-by <Long: number-of-offsets> : Reset offsets shifting current offset by ‘n’, where ‘n’ can be positive or negative.
  • –from-file : Reset offsets to values defined in CSV file.
  • –to-current : Resets offsets to current offset.
  • –by-duration <String: duration> : Reset offsets to offset by duration from current timestamp. Format: ‘PnDTnHnMnS’
  • –to-offset : Reset offsets to a specific offset.

Please note, that out of range offsets will be adjusted to available offset end. For example, if offset end is at 10 and offset shift request is
of 15, then, offset at 10 will actually be selected.

Please note, that out of range offsets will be adjusted to available offset end. For example, if offset end is at 10 and offset shift request is of 15, then, offset at 10 will actually be selected.

For example, to reset offsets of a consumer group to the latest offset:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --group consumergroup1 --topic topic1 --to-latest

  TOPIC                          PARTITION  NEW-OFFSET
  topic1                         0          0

If you are using the old high-level consumer and storing the group metadata in ZooKeeper (i.e. offsets.storage=zookeeper), pass
--zookeeper instead of --bootstrap-server:

  > bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --list

Adding servers to a Kafka cluster is easy, just assign them a unique broker id and start up Kafka on your new servers. However these new servers will not automatically be assigned any data partitions, so unless partitions are moved to them they won’t be doing any work until new topics are created. So usually when you add machines to your cluster you will want to migrate some existing data to these machines.

Adding servers to a Kafka cluster is easy, just assign them a unique broker id and start up Kafka on your new servers. However these new servers will not automatically be assigned any data partitions, so unless partitions are moved to them they won’t be doing any work until new topics are created. So usually when you add machines to your cluster you will want to migrate some existing data to these machines.

The process of migrating data is manually initiated but fully automated. Under the covers what happens is that Kafka will add the new server as a follower of the partition it is migrating and allow it to fully replicate the existing data in that partition. When the new server has fully replicated the contents of this partition and joined the in-sync replica one of the existing replicas will delete their partition’s data.

The partition reassignment tool can be used to move partitions across brokers. An ideal partition distribution would ensure even data load and partition sizes across all brokers. The partition reassignment tool does not have the capability to automatically study the data distribution in a Kafka cluster and move partitions around to attain an even load distribution. As such, the admin has to figure out which topics or partitions should be moved around.

The partition reassignment tool can run in 3 mutually exclusive modes:

  • –generate: In this mode, given a list of topics and a list of brokers, the tool generates a candidate reassignment to move all partitions of the specified topics to the new brokers. This option merely provides a convenient way to generate a partition reassignment plan given a list of topics and target brokers.
  • –execute: In this mode, the tool kicks off the reassignment of partitions based on the user provided reassignment plan. (using the –reassignment-json-file option). This can either be a custom reassignment plan hand crafted by the admin or provided by using the –generate option
  • –verify: In this mode, the tool verifies the status of the reassignment for all partitions listed during the last –execute. The status can be either of successfully completed, failed or in progress

The partition reassignment tool can be used to move some topics off of the current set of brokers to the newly added brokers. This is typically useful while expanding an existing cluster since it is easier to move entire topics to the new set of brokers, than moving one partition at a time. When used to do this, the user should provide a list of topics that should be moved to the new set of brokers and a target list of new brokers. The tool then evenly distributes all partitions for the given list of topics across the new set of brokers. During this move, the replication factor of the topic is kept constant. Effectively the replicas for all partitions for the input list of topics are moved from the old set of brokers to the newly added brokers.

The partition reassignment tool can be used to move some topics off of the current set of brokers to the newly added brokers. This is typically useful while expanding an existing cluster since it is easier to move entire topics to the new set of brokers, than moving one partition at a time. When used to do this, the user should provide a list of topics that should be moved to the new set of brokers and a target list of new brokers. The tool then evenly distributes all partitions for the given list of topics across the new set of brokers. During this move, the replication factor of the topic is kept constant. Effectively the replicas for all partitions for the input list of topics are moved from the old set of brokers to the newly added brokers.

For instance, the following example will move all partitions for topics foo1,foo2 to the new set of brokers 5,6. At the end of this move, all partitions for topics foo1 and foo2 will exist on brokers 5,6.

Since the tool accepts the input list of topics as a json file, you first need to identify the topics you want to move and create the json file as follows:

  > cat topics-to-move.json
  {"topics": [{"topic": "foo1"},
              {"topic": "foo2"}],
  "version":1
  }

Once the json file is ready, use the partition reassignment tool to generate a candidate assignment:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --topics-to-move-json-file topics-to-move.json --broker-list "5,6" --generate
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":2,"replicas":[1,2]},
                {"topic":"foo1","partition":0,"replicas":[3,4]},
                {"topic":"foo2","partition":2,"replicas":[1,2]},
                {"topic":"foo2","partition":0,"replicas":[3,4]},
                {"topic":"foo1","partition":1,"replicas":[2,3]},
                {"topic":"foo2","partition":1,"replicas":[2,3]}]
  }

  Proposed partition reassignment configuration

  {"version":1,
  "partitions":[{"topic":"foo1","partition":2,"replicas":[5,6]},
                {"topic":"foo1","partition":0,"replicas":[5,6]},
                {"topic":"foo2","partition":2,"replicas":[5,6]},
                {"topic":"foo2","partition":0,"replicas":[5,6]},
                {"topic":"foo1","partition":1,"replicas":[5,6]},
                {"topic":"foo2","partition":1,"replicas":[5,6]}]
  }

Once the json file is ready, use the partition reassignment tool to generate a candidate assignment:

The tool generates a candidate assignment that will move all partitions from topics foo1,foo2 to brokers 5,6. Note, however, that at this point, the partition movement has not started, it merely tells you the current assignment and the proposed new assignment. The current assignment should be saved in case you want to rollback to it. The new assignment should be saved in a json file (e.g. expand-cluster-reassignment.json) to be input to the tool with the –execute option as follows:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file expand-cluster-reassignment.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":2,"replicas":[1,2]},
                {"topic":"foo1","partition":0,"replicas":[3,4]},
                {"topic":"foo2","partition":2,"replicas":[1,2]},
                {"topic":"foo2","partition":0,"replicas":[3,4]},
                {"topic":"foo1","partition":1,"replicas":[2,3]},
                {"topic":"foo2","partition":1,"replicas":[2,3]}]
  }

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started reassignment of partitions
  {"version":1,
  "partitions":[{"topic":"foo1","partition":2,"replicas":[5,6]},
                {"topic":"foo1","partition":0,"replicas":[5,6]},
                {"topic":"foo2","partition":2,"replicas":[5,6]},
                {"topic":"foo2","partition":0,"replicas":[5,6]},
                {"topic":"foo1","partition":1,"replicas":[5,6]},
                {"topic":"foo2","partition":1,"replicas":[5,6]}]
  }

Finally, the –verify option can be used with the tool to check the status of the partition reassignment. Note that the same expand-cluster-reassignment.json (used with the –execute option) should be used with the –verify option:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file expand-cluster-reassignment.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo1,0] completed successfully
  Reassignment of partition [foo1,1] is in progress
  Reassignment of partition [foo1,2] is in progress
  Reassignment of partition [foo2,0] completed successfully
  Reassignment of partition [foo2,1] completed successfully
  Reassignment of partition [foo2,2] completed successfully

The partition reassignment tool can also be used to selectively move replicas of a partition to a specific set of brokers. When used in this manner, it is assumed that the user knows the reassignment plan and does not require the tool to generate a candidate reassignment, effectively skipping the –generate step and moving straight to the –execute step

The partition reassignment tool can also be used to selectively move replicas of a partition to a specific set of brokers. When used in this manner, it is assumed that the user knows the reassignment plan and does not require the tool to generate a candidate reassignment, effectively skipping the –generate step and moving straight to the –execute step

For instance, the following example moves partition 0 of topic foo1 to brokers 5,6 and partition 1 of topic foo2 to brokers 2,3:

The first step is to hand craft the custom reassignment plan in a json file:

  > cat custom-reassignment.json
  {"version":1,"partitions":[{"topic":"foo1","partition":0,"replicas":[5,6]},{"topic":"foo2","partition":1,"replicas":[2,3]}]}

Then, use the json file with the –execute option to start the reassignment process:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file custom-reassignment.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[1,2]},
                {"topic":"foo2","partition":1,"replicas":[3,4]}]
  }

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started reassignment of partitions
  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[5,6]},
                {"topic":"foo2","partition":1,"replicas":[2,3]}]
  }

Then, use the json file with the –execute option to start the reassignment process:

The –verify option can be used with the tool to check the status of the partition reassignment. Note that the same custom-reassignment.json (used with the –execute option) should be used with the –verify option:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file custom-reassignment.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo1,0] completed successfully
  Reassignment of partition [foo2,1] completed successfully

The partition reassignment tool does not have the ability to automatically generate a reassignment plan for decommissioning brokers yet. As such, the admin has to come up with a reassignment plan to move the replica for all partitions hosted on the broker to be decommissioned, to the rest of the brokers. This can be relatively tedious as the reassignment needs to ensure that all the replicas are not moved from the decommissioned broker to only one other broker. To make this process effortless, we plan to add tooling support for decommissioning brokers in the future.

Increasing the replication factor of an existing partition is easy. Just specify the extra replicas in the custom reassignment json file and use it with the –execute option to increase the replication factor of the specified partitions.

The partition reassignment tool does not have the ability to automatically generate a reassignment plan for decommissioning brokers yet. As such, the admin has to come up with a reassignment plan to move the replica for all partitions hosted on the broker to be decommissioned, to the rest of the brokers. This can be relatively tedious as the reassignment needs to ensure that all the replicas are not moved from the decommissioned broker to only one other broker. To make this process effortless, we plan to add tooling support for decommissioning brokers in the future.Increasing the replication factor of an existing partition is easy. Just specify the extra replicas in the custom reassignment json file and use it with the –execute option to increase the replication factor of the specified partitions.

For instance, the following example increases the replication factor of partition 0 of topic foo from 1 to 3. Before increasing the replication factor, the partition’s only replica existed on broker 5. As part of increasing the replication factor, we will add more replicas on brokers 6 and 7.

The first step is to hand craft the custom reassignment plan in a json file:

  > cat increase-replication-factor.json
  {"version":1,
  "partitions":[{"topic":"foo","partition":0,"replicas":[5,6,7]}]}

Then, use the json file with the –execute option to start the reassignment process:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file increase-replication-factor.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo","partition":0,"replicas":[5]}]}

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started reassignment of partitions
  {"version":1,
  "partitions":[{"topic":"foo","partition":0,"replicas":[5,6,7]}]}

Then, use the json file with the –execute option to start the reassignment process:

The –verify option can be used with the tool to check the status of the partition reassignment. Note that the same increase-replication-factor.json (used with the –execute option) should be used with the –verify option:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file increase-replication-factor.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo,0] completed successfully

You can also verify the increase in replication factor with the kafka-topics tool:

  > bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic foo --describe
  Topic:foo	PartitionCount:1	ReplicationFactor:3	Configs:
    Topic: foo	Partition: 0	Leader: 5	Replicas: 5,6,7	Isr: 5,6,7

Kafka lets you apply a throttle to replication traffic, setting an upper bound on the bandwidth used to move replicas from machine to machine. This is useful when rebalancing a cluster, bootstrapping a new broker or adding or removing brokers, as it limits the impact these data-intensive operations will have on users.

You can also verify the increase in replication factor with the kafka-topics tool:Kafka lets you apply a throttle to replication traffic, setting an upper bound on the bandwidth used to move replicas from machine to machine. This is useful when rebalancing a cluster, bootstrapping a new broker or adding or removing brokers, as it limits the impact these data-intensive operations will have on users.

There are two interfaces that can be used to engage a throttle. The simplest, and safest, is to apply a throttle when invoking the kafka-reassign-partitions.sh, but kafka-configs.sh can also be used to view and alter the throttle values directly.

There are two interfaces that can be used to engage a throttle. The simplest, and safest, is to apply a throttle when invoking the kafka-reassign-partitions.sh, but kafka-configs.sh can also be used to view and alter the throttle values directly.

So for example, if you were to execute a rebalance, with the below command, it would move partitions at no more than 50MB/s.

$ bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --execute --reassignment-json-file bigger-cluster.json --throttle 50000000

When you execute this script you will see the throttle engage:

  The throttle limit was set to 50000000 B/s
  Successfully started reassignment of partitions.

So for example, if you were to execute a rebalance, with the below command, it would move partitions at no more than 50MB/s.When you execute this script you will see the throttle engage:

Should you wish to alter the throttle, during a rebalance, say to increase the throughput so it completes quicker, you can do this by re-running the execute command passing the same reassignment-json-file:

$ bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092  --execute --reassignment-json-file bigger-cluster.json --throttle 700000000
  There is an existing assignment running.
  The throttle limit was set to 700000000 B/s

Once the rebalance completes the administrator can check the status of the rebalance using the –verify option.
If the rebalance has completed, the throttle will be removed via the –verify command. It is important that
administrators remove the throttle in a timely manner once rebalancing completes by running the command with
the –verify option. Failure to do so could cause regular replication traffic to be throttled.

When the –verify option is executed, and the reassignment has completed, the script will confirm that the throttle was removed:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092  --verify --reassignment-json-file bigger-cluster.json
  Status of partition reassignment:
  Reassignment of partition [my-topic,1] completed successfully
  Reassignment of partition [mytopic,0] completed successfully
  Throttle was removed.

The administrator can also validate the assigned configs using the kafka-configs.sh. There are two pairs of throttle
configuration used to manage the throttling process. First pair refers to the throttle value itself. This is configured, at a broker
level, using the dynamic properties:

    leader.replication.throttled.rate
    follower.replication.throttled.rate

Then there is the configuration pair of enumerated sets of throttled replicas:

    leader.replication.throttled.replicas
    follower.replication.throttled.replicas

Which are configured per topic.

All four config values are automatically assigned by kafka-reassign-partitions.sh (discussed below).

To view the throttle limit configuration:

  > bin/kafka-configs.sh --describe --bootstrap-server localhost:9092 --entity-type brokers
  Configs for brokers '2' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000
  Configs for brokers '1' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000

This shows the throttle applied to both leader and follower side of the replication protocol. By default both sides
are assigned the same throttled throughput value.

To view the list of throttled replicas:

  > bin/kafka-configs.sh --describe --bootstrap-server localhost:9092 --entity-type topics
  Configs for topic 'my-topic' are leader.replication.throttled.replicas=1:102,0:101,
      follower.replication.throttled.replicas=1:101,0:102

Here we see the leader throttle is applied to partition 1 on broker 102 and partition 0 on broker 101. Likewise the
follower throttle is applied to partition 1 on
broker 101 and partition 0 on broker 102.

By default kafka-reassign-partitions.sh will apply the leader throttle to all replicas that exist before the
rebalance, any one of which might be leader.
It will apply the follower throttle to all move destinations. So if there is a partition with replicas on brokers
101,102, being reassigned to 102,103, a leader throttle,
for that partition, would be applied to 101,102 and a follower throttle would be applied to 103 only.

If required, you can also use the –alter switch on kafka-configs.sh to alter the throttle configurations manually.

Safe usage of throttled replication

Some care should be taken when using throttled replication. In particular:

The throttle should be removed in a timely manner once reassignment completes (by running kafka-reassign-partitions.sh
–verify).

The throttle should be removed in a timely manner once reassignment completes (by running kafka-reassign-partitions.sh –verify).

If the throttle is set too low, in comparison to the incoming write rate, it is possible for replication to not
make progress. This occurs when:

max(BytesInPerSec) > throttle

Where BytesInPerSec is the metric that monitors the write throughput of producers into each broker.

The administrator can monitor whether replication is making progress, during the rebalance, using the metric:

kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+)

The lag should constantly decrease during replication. If the metric does not decrease the administrator should
increase the
throttle throughput as described above.

Quotas overrides and defaults may be configured at (user, client-id), user or client-id levels as described

Quotas overrides and defaults may be configured at (user, client-id), user or client-id levels as described here . By default, clients receive an unlimited quota. It is possible to set custom quotas for each (user, client-id), user or client-id group.

Configure custom quota for (user=user1, client-id=clientA):

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
  Updated config for entity: user-principal 'user1', client-id 'clientA'.

Configure custom quota for user=user1:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1
  Updated config for entity: user-principal 'user1'.

Configure custom quota for client-id=clientA:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type clients --entity-name clientA
  Updated config for entity: client-id 'clientA'.

It is possible to set default quotas for each (user, client-id), user or client-id group by specifying option instead of .

Configure custom quota for user=user1:Configure custom quota for client-id=clientA:It is possible to set default quotas for each (user, client-id), user or client-id group by specifyingoption instead of

Configure default client-id quota for user=userA:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1 --entity-type clients --entity-default
  Updated config for entity: user-principal 'user1', default client-id.

Configure default quota for user:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-default
  Updated config for entity: default user-principal.

Configure default quota for client-id:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type clients --entity-default
  Updated config for entity: default client-id.

Here’s how to describe the quota for a given (user, client-id):

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
  Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

Describe quota for a given user:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-name user1
  Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

Describe quota for a given client-id:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type clients --entity-name clientA
  Configs for client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

If entity name is not specified, all entities of the specified type are described. For example, describe all users:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users
  Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  Configs for default user-principal are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

Similarly for (user, client):

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-type clients
  Configs for user-principal 'user1', default client-id are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

Some deployments will need to manage a data pipeline that spans multiple datacenters. Our recommended approach to this is to deploy a local Kafka cluster in each datacenter, with application instances in each datacenter interacting only with their local cluster and mirroring data between clusters (see the documentation on

Configure default quota for user:Configure default quota for client-id:Here’s how to describe the quota for a given (user, client-id):Describe quota for a given user:Describe quota for a given client-id:If entity name is not specified, all entities of the specified type are described. For example, describe all users:Similarly for (user, client):Some deployments will need to manage a data pipeline that spans multiple datacenters. Our recommended approach to this is to deploy a local Kafka cluster in each datacenter, with application instances in each datacenter interacting only with their local cluster and mirroring data between clusters (see the documentation on Geo-Replication for how to do this).

This deployment pattern allows datacenters to act as independent entities and allows us to manage and tune inter-datacenter replication centrally. This allows each facility to stand alone and operate even if the inter-datacenter links are unavailable: when this occurs the mirroring falls behind until the link is restored at which time it catches up.

For applications that need a global view of all data you can use mirroring to provide clusters which have aggregate data mirrored from the local clusters in datacenters. These aggregate clusters are used for reads by applications that require the full data set.

This is not the only possible deployment pattern. It is possible to read from or write to a remote Kafka cluster over the WAN, though obviously this will add whatever latency is required to get the cluster.

Kafka naturally batches data in both the producer and consumer so it can achieve high-throughput even over a high-latency connection. To allow this though it may be necessary to increase the TCP socket buffer sizes for the producer, consumer, and broker using the socket.send.buffer.bytes and socket.receive.buffer.bytes configurations. The appropriate way to set this is documented here.

It is generally advisable to run a Kafka cluster that spans multiple datacenters over a high-latency link. This will incur very high replication latency both for Kafka writes and ZooKeeper writes, and neither Kafka nor ZooKeeper will remain available in all locations if the network between locations is unavailable.

Kafka administrators can define data flows that cross the boundaries of individual Kafka clusters, data centers, or geo-regions. Such event streaming setups are often needed for organizational, technical, or legal requirements. Common scenarios include:

  • Geo-replication
  • Disaster recovery
  • Feeding edge clusters into a central, aggregate cluster
  • Physical isolation of clusters (such as production vs. testing)
  • Cloud migration or hybrid cloud deployments
  • Legal and compliance requirements

Administrators can set up such inter-cluster data flows with Kafka’s MirrorMaker (version 2), a tool to replicate data between different Kafka environments in a streaming manner. MirrorMaker is built on top of the Kafka Connect framework and supports features such as:

  • Replicates topics (data plus configurations)
  • Replicates consumer groups including offsets to migrate applications between clusters
  • Replicates ACLs
  • Preserves partitioning
  • Automatically detects new topics and partitions
  • Provides a wide range of metrics, such as end-to-end replication latency across multiple data centers/clusters
  • Fault-tolerant and horizontally scalable operations

Note: Geo-replication with MirrorMaker replicates data across Kafka clusters. This inter-cluster replication is different from Kafka’s intra-cluster replication, which replicates data within the same Kafka cluster.

With MirrorMaker, Kafka administrators can replicate topics, topic configurations, consumer groups and their offsets, and ACLs from one or more source Kafka clusters to one or more target Kafka clusters, i.e., across cluster environments. In a nutshell, MirrorMaker uses Connectors to consume from source clusters and produce to target clusters.

These directional flows from source to target clusters are called replication flows. They are defined with the format {source_cluster}->{target_cluster} in the MirrorMaker configuration file as described later. Administrators can create complex replication topologies based on these flows.

Here are some example patterns:

  • Active/Active high availability deployments: A->B, B->A
  • Active/Passive or Active/Standby high availability deployments: A->B
  • Aggregation (e.g., from many clusters to one): A->K, B->K, C->K
  • Fan-out (e.g., from one to many clusters): K->A, K->B, K->C
  • Forwarding: A->B, B->C, C->D

By default, a flow replicates all topics and consumer groups. However, each replication flow can be configured independently. For instance, you can define that only specific topics or consumer groups are replicated from the source cluster to the target cluster.

Here is a first example on how to configure data replication from a primary cluster to a secondary cluster (an active/passive setup):

# Basic settings
clusters = primary, secondary
primary.bootstrap.servers = broker3-primary:9092
secondary.bootstrap.servers = broker5-secondary:9092

# Define replication flows
primary->secondary.enabled = true
primary->secondary.topics = foobar-topic, quux-.*

The following sections describe how to configure and run a dedicated MirrorMaker cluster. If you want to run MirrorMaker within an existing Kafka Connect cluster or other supported deployment setups, please refer to KIP-382: MirrorMaker 2.0 and be aware that the names of configuration settings may vary between deployment modes.

Beyond what’s covered in the following sections, further examples and information on configuration settings are available at:

The MirrorMaker configuration file is typically named connect-mirror-maker.properties. You can configure a variety of components in this file:

  • MirrorMaker settings: global settings including cluster definitions (aliases), plus custom settings per replication flow
  • Kafka Connect and connector settings
  • Kafka producer, consumer, and admin client settings

Example: Define MirrorMaker settings (explained in more detail later).

# Global settings
clusters = us-west, us-east   # defines cluster aliases
us-west.bootstrap.servers = broker3-west:9092
us-east.bootstrap.servers = broker5-east:9092

topics = .*   # all topics to be replicated by default

# Specific replication flow settings (here: flow from us-west to us-east)
us-west->us-east.enabled = true
us-west->us.east.topics = foo.*, bar.*  # override the default above

MirrorMaker is based on the Kafka Connect framework. Any Kafka Connect, source connector, and sink connector settings as described in the documentation chapter on Kafka Connect can be used directly in the MirrorMaker configuration, without having to change or prefix the name of the configuration setting.

Example: Define custom Kafka Connect settings to be used by MirrorMaker.

# Setting Kafka Connect defaults for MirrorMaker
tasks.max = 5

Most of the default Kafka Connect settings work well for MirrorMaker out-of-the-box, with the exception of tasks.max. In order to evenly distribute the workload across more than one MirrorMaker process, it is recommended to set tasks.max to at least 2 (preferably higher) depending on the available hardware resources and the total number of topic-partitions to be replicated.

You can further customize MirrorMaker’s Kafka Connect settings per source or target cluster (more precisely, you can specify Kafka Connect worker-level configuration settings “per connector”). Use the format of {cluster}.{config_name} in the MirrorMaker configuration file.

Example: Define custom connector settings for the us-west cluster.

# us-west custom settings
us-west.offset.storage.topic = my-mirrormaker-offsets

MirrorMaker internally uses the Kafka producer, consumer, and admin clients. Custom settings for these clients are often needed. To override the defaults, use the following format in the MirrorMaker configuration file:

  • {source}.consumer.{consumer_config_name}
  • {target}.producer.{producer_config_name}
  • {source_or_target}.admin.{admin_config_name}

Example: Define custom producer, consumer, admin client settings.

# us-west cluster (from which to consume)
us-west.consumer.isolation.level = read_committed
us-west.admin.bootstrap.servers = broker57-primary:9092

# us-east cluster (to which to produce)
us-east.producer.compression.type = gzip
us-east.producer.buffer.memory = 32768
us-east.admin.bootstrap.servers = broker8-secondary:9092

To define a replication flow, you must first define the respective source and target Kafka clusters in the MirrorMaker configuration file.

  • clusters (required): comma-separated list of Kafka cluster “aliases”
  • {clusterAlias}.bootstrap.servers (required): connection information for the specific cluster; comma-separated list of “bootstrap” Kafka brokers

Example: Define two cluster aliases primary and secondary, including their connection information.

clusters = primary, secondary
primary.bootstrap.servers = broker10-primary:9092,broker-11-primary:9092
secondary.bootstrap.servers = broker5-secondary:9092,broker6-secondary:9092

Secondly, you must explicitly enable individual replication flows with {source}->{target}.enabled = true as needed. Remember that flows are directional: if you need two-way (bidirectional) replication, you must enable flows in both directions.

# Enable replication from primary to secondary
primary->secondary.enabled = true

By default, a replication flow will replicate all but a few special topics and consumer groups from the source cluster to the target cluster, and automatically detect any newly created topics and groups. The names of replicated topics in the target cluster will be prefixed with the name of the source cluster (see section further below). For example, the topic foo in the source cluster us-west would be replicated to a topic named us-west.foo in the target cluster us-east.

The subsequent sections explain how to customize this basic setup according to your needs.

The configuration of a replication flow is a combination of top-level default settings (e.g., topics), on top of which flow-specific settings, if any, are applied (e.g., us-west->us-east.topics). To change the top-level defaults, add the respective top-level setting to the MirrorMaker configuration file. To override the defaults for a specific replication flow only, use the syntax format {source}->{target}.{config.name}.

The most important settings are:

  • topics: list of topics or a regular expression that defines which topics in the source cluster to replicate (default: topics = .*)
  • topics.exclude: list of topics or a regular expression to subsequently exclude topics that were matched by the topics setting (default: topics.exclude = .*[\-\.]internal, .*\.replica, __.*)
  • groups: list of topics or regular expression that defines which consumer groups in the source cluster to replicate (default: groups = .*)
  • groups.exclude: list of topics or a regular expression to subsequently exclude consumer groups that were matched by the groups setting (default: groups.exclude = console-consumer-.*, connect-.*, __.*)
  • {source}->{target}.enable: set to true to enable the replication flow (default: false)

Example:

# Custom top-level defaults that apply to all replication flows
topics = .*
groups = consumer-group1, consumer-group2

# Don't forget to enable a flow!
us-west->us-east.enabled = true

# Custom settings for specific replication flows
us-west->us-east.topics = foo.*
us-west->us-east.groups = bar.*
us-west->us-east.emit.heartbeats = false

Additional configuration settings are supported, some of which are listed below. In most cases, you can leave these settings at their default values. See MirrorMakerConfig and MirrorConnectorConfig for further details.

  • refresh.topics.enabled: whether to check for new topics in the source cluster periodically (default: true)
  • refresh.topics.interval.seconds: frequency of checking for new topics in the source cluster; lower values than the default may lead to performance degradation (default: 600, every ten minutes)
  • refresh.groups.enabled: whether to check for new consumer groups in the source cluster periodically (default: true)
  • refresh.groups.interval.seconds: frequency of checking for new consumer groups in the source cluster; lower values than the default may lead to performance degradation (default: 600, every ten minutes)
  • sync.topic.configs.enabled: whether to replicate topic configurations from the source cluster (default: true)
  • sync.topic.acls.enabled: whether to sync ACLs from the source cluster (default: true)
  • emit.heartbeats.enabled: whether to emit heartbeats periodically (default: true)
  • emit.heartbeats.interval.seconds: frequency at which heartbeats are emitted (default: 1, every one seconds)
  • heartbeats.topic.replication.factor: replication factor of MirrorMaker’s internal heartbeat topics (default: 3)
  • emit.checkpoints.enabled: whether to emit MirrorMaker’s consumer offsets periodically (default: true)
  • emit.checkpoints.interval.seconds: frequency at which checkpoints are emitted (default: 60, every minute)
  • checkpoints.topic.replication.factor: replication factor of MirrorMaker’s internal checkpoints topics (default: 3)
  • sync.group.offsets.enabled: whether to periodically write the translated offsets of replicated consumer groups (in the source cluster) to __consumer_offsets topic in target cluster, as long as no active consumers in that group are connected to the target cluster (default: false)
  • sync.group.offsets.interval.seconds: frequency at which consumer group offsets are synced (default: 60, every minute)
  • offset-syncs.topic.replication.factor: replication factor of MirrorMaker’s internal offset-sync topics (default: 3)

MirrorMaker supports the same security settings as Kafka Connect, so please refer to the linked section for further information.

Example: Encrypt communication between MirrorMaker and the us-east cluster.

us-east.security.protocol=SSL
us-east.ssl.truststore.location=/path/to/truststore.jks
us-east.ssl.truststore.password=my-secret-password
us-east.ssl.keystore.location=/path/to/keystore.jks
us-east.ssl.keystore.password=my-secret-password
us-east.ssl.key.password=my-secret-password

Replicated topics in a target cluster—sometimes called remote topics—are renamed according to a replication policy. MirrorMaker uses this policy to ensure that events (aka records, messages) from different clusters are not written to the same topic-partition. By default as per DefaultReplicationPolicy, the names of replicated topics in the target clusters have the format {source}.{source_topic_name}:

us-west         us-east
=========       =================
                bar-topic
foo-topic  -->  us-west.foo-topic

You can customize the separator (default: .) with the replication.policy.separator setting:

# Defining a custom separator
us-west->us-east.replication.policy.separator = _

If you need further control over how replicated topics are named, you can implement a custom ReplicationPolicy and override replication.policy.class (default is DefaultReplicationPolicy) in the MirrorMaker configuration.

MirrorMaker processes share configuration via their target Kafka clusters. This behavior may cause conflicts when configurations differ among MirrorMaker processes that operate against the same target cluster.

For example, the following two MirrorMaker processes would be racy:

# Configuration of process 1
A->B.enabled = true
A->B.topics = foo

# Configuration of process 2
A->B.enabled = true
A->B.topics = bar

In this case, the two processes will share configuration via cluster B, which causes a conflict. Depending on which of the two processes is the elected “leader”, the result will be that either the topic foo or the topic bar is replicated, but not both.

It is therefore important to keep the MirrorMaker configration consistent across replication flows to the same target cluster. This can be achieved, for example, through automation tooling or by using a single, shared MirrorMaker configuration file for your entire organization.

To minimize latency (“producer lag”), it is recommended to locate MirrorMaker processes as close as possible to their target clusters, i.e., the clusters that it produces data to. That’s because Kafka producers typically struggle more with unreliable or high-latency network connections than Kafka consumers.

First DC          Second DC
==========        =========================
primary --------- MirrorMaker --> secondary
(remote)                           (local)

To run such a “consume from remote, produce to local” setup, run the MirrorMaker processes close to and preferably in the same location as the target clusters, and explicitly set these “local” clusters in the --clusters command line parameter (blank-separated list of cluster aliases):

# Run in secondary's data center, reading from the remote `primary` cluster
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters secondary

The --clusters secondary tells the MirrorMaker process that the given cluster(s) are nearby, and prevents it from replicating data or sending configuration to clusters at other, remote locations.

Thetells the MirrorMaker process that the given cluster(s) are nearby, and prevents it from replicating data or sending configuration to clusters at other, remote locations.

The following example shows the basic settings to replicate topics from a primary to a secondary Kafka environment, but not from the secondary back to the primary. Please be aware that most production setups will need further configuration, such as security settings.

# Unidirectional flow (one-way) from primary to secondary cluster
primary.bootstrap.servers = broker1-primary:9092
secondary.bootstrap.servers = broker2-secondary:9092

primary->secondary.enabled = true
secondary->primary.enabled = false

primary->secondary.topics = foo.*  # only replicate some topics

The following example shows the basic settings to replicate topics between two clusters in both ways. Please be aware that most production setups will need further configuration, such as security settings.

# Bidirectional flow (two-way) between us-west and us-east clusters
clusters = us-west, us-east
us-west.bootstrap.servers = broker1-west:9092,broker2-west:9092
Us-east.bootstrap.servers = broker3-east:9092,broker4-east:9092

us-west->us-east.enabled = true
us-east->us-west.enabled = true

Note on preventing replication “loops” (where topics will be originally replicated from A to B, then the replicated topics will be replicated yet again from B to A, and so forth): As long as you define the above flows in the same MirrorMaker configuration file, you do not need to explicitly add topics.exclude settings to prevent replication loops between the two clusters.

Let’s put all the information from the previous sections together in a larger example. Imagine there are three data centers (west, east, north), with two Kafka clusters in each data center (e.g., west-1, west-2). The example in this section shows how to configure MirrorMaker (1) for Active/Active replication within each data center, as well as (2) for Cross Data Center Replication (XDCR).

First, define the source and target clusters along with their replication flows in the configuration:

# Basic settings
clusters: west-1, west-2, east-1, east-2, north-1, north-2
west-1.bootstrap.servers = ...
west-2.bootstrap.servers = ...
east-1.bootstrap.servers = ...
east-2.bootstrap.servers = ...
north-1.bootstrap.servers = ...
north-2.bootstrap.servers = ...

# Replication flows for Active/Active in West DC
west-1->west-2.enabled = true
west-2->west-1.enabled = true

# Replication flows for Active/Active in East DC
east-1->east-2.enabled = true
east-2->east-1.enabled = true

# Replication flows for Active/Active in North DC
north-1->north-2.enabled = true
north-2->north-1.enabled = true

# Replication flows for XDCR via west-1, east-1, north-1
west-1->east-1.enabled  = true
west-1->north-1.enabled = true
east-1->west-1.enabled  = true
east-1->north-1.enabled = true
north-1->west-1.enabled = true
north-1->east-1.enabled = true

Then, in each data center, launch one or more MirrorMaker as follows:

# In West DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters west-1 west-2

# In East DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters east-1 east-2

# In North DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters north-1 north-2

With this configuration, records produced to any cluster will be replicated within the data center, as well as across to other data centers. By providing the --clusters parameter, we ensure that each MirrorMaker process produces data to nearby clusters only.

Note: The --clusters parameter is, technically, not required here. MirrorMaker will work fine without it. However, throughput may suffer from “producer lag” between data centers, and you may incur unnecessary data transfer costs.

You can run as few or as many MirrorMaker processes (think: nodes, servers) as needed. Because MirrorMaker is based on Kafka Connect, MirrorMaker processes that are configured to replicate the same Kafka clusters run in a distributed setup: They will find each other, share configuration (see section below), load balance their work, and so on. If, for example, you want to increase the throughput of replication flows, one option is to run additional MirrorMaker processes in parallel.

To start a MirrorMaker process, run the command:

$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties

After startup, it may take a few minutes until a MirrorMaker process first begins to replicate data.

Optionally, as described previously, you can set the parameter --clusters to ensure that the MirrorMaker process produces data to nearby clusters only.

# Note: The cluster alias us-west must be defined in the configuration file
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties \
            --clusters us-west

Note when testing replication of consumer groups: By default, MirrorMaker does not replicate consumer groups created by the kafka-console-consumer.sh tool, which you might use to test your MirrorMaker setup on the command line. If you do want to replicate these consumer groups as well, set the groups.exclude configuration accordingly (default: groups.exclude = console-consumer-.*, connect-.*, __.*). Remember to update the configuration again once you completed your testing.

You can stop a running MirrorMaker process by sending a SIGTERM signal with the command:

$ kill <MirrorMaker pid>

To make configuration changes take effect, the MirrorMaker process(es) must be restarted.

It is recommended to monitor MirrorMaker processes to ensure all defined replication flows are up and running correctly. MirrorMaker is built on the Connect framework and inherits all of Connect’s metrics, such source-record-poll-rate. In addition, MirrorMaker produces its own metrics under the kafka.connect.mirror metric group. Metrics are tagged with the following properties:

  • source: alias of source cluster (e.g., primary)
  • target: alias of target cluster (e.g., secondary)
  • topic: replicated topic on target cluster
  • partition: partition being replicated

Metrics are tracked for each replicated topic. The source cluster can be inferred from the topic name. For example, replicating topic1 from primary->secondary will yield metrics like:

  • target=secondary
  • topic=primary.topic1
  • partition=1

The following metrics are emitted:

# MBean: kafka.connect.mirror:type=MirrorSourceConnector,target=([-.w]+),topic=([-.w]+),partition=([0-9]+)

record-count            # number of records replicated source -> target
record-age-ms           # age of records when they are replicated
record-age-ms-min
record-age-ms-max
record-age-ms-avg
replication-latency-ms  # time it takes records to propagate source->target
replication-latency-ms-min
replication-latency-ms-max
replication-latency-ms-avg
byte-rate               # average number of bytes/sec in replicated records

# MBean: kafka.connect.mirror:type=MirrorCheckpointConnector,source=([-.w]+),target=([-.w]+)

checkpoint-latency-ms   # time it takes to replicate consumer offsets
checkpoint-latency-ms-min
checkpoint-latency-ms-max
checkpoint-latency-ms-avg

These metrics do not differentiate between created-at and log-append timestamps.

As a highly scalable event streaming platform, Kafka is used by many users as their central nervous system, connecting in real-time a wide range of different systems and applications from various teams and lines of businesses. Such multi-tenant cluster environments command proper control and management to ensure the peaceful coexistence of these different needs. This section highlights features and best practices to set up such shared environments, which should help you operate clusters that meet SLAs/OLAs and that minimize potential collateral damage caused by “noisy neighbors”.

Multi-tenancy is a many-sided subject, including but not limited to:

  • Creating user spaces for tenants (sometimes called namespaces)
  • Configuring topics with data retention policies and more
  • Securing topics and clusters with encryption, authentication, and authorization
  • Isolating tenants with quotas and rate limits
  • Monitoring and metering
  • Inter-cluster data sharing (cf. geo-replication)

Kafka administrators operating a multi-tenant cluster typically need to define user spaces for each tenant. For the purpose of this section, “user spaces” are a collection of topics, which are grouped together under the management of a single entity or user.

In Kafka, the main unit of data is the topic. Users can create and name each topic. They can also delete them, but it is not possible to rename a topic directly. Instead, to rename a topic, the user must create a new topic, move the messages from the original topic to the new, and then delete the original. With this in mind, it is recommended to define logical spaces, based on an hierarchical topic naming structure. This setup can then be combined with security features, such as prefixed ACLs, to isolate different spaces and tenants, while also minimizing the administrative overhead for securing the data in the cluster.

These logical user spaces can be grouped in different ways, and the concrete choice depends on how your organization prefers to use your Kafka clusters. The most common groupings are as follows.

By team or organizational unit: Here, the team is the main aggregator. In an organization where teams are the main user of the Kafka infrastructure, this might be the best grouping.

Example topic naming structure:

  • <organization>.<team>.<dataset>.<event-name>
    (e.g., “acme.infosec.telemetry.logins”)

By project or product: Here, a team manages more than one project. Their credentials will be different for each project, so all the controls and settings will always be project related.

Example topic naming structure:

  • <project>.<product>.<event-name>
    (e.g., “mobility.payments.suspicious”)

Certain information should normally not be put in a topic name, such as information that is likely to change over time (e.g., the name of the intended consumer) or that is a technical detail or metadata that is available elsewhere (e.g., the topic’s partition count and other configuration settings).

To enforce a topic naming structure, several options are available:

  • Use prefix ACLs (cf. KIP-290) to enforce a common prefix for topic names. For example, team A may only be permitted to create topics whose names start with payments.teamA..
  • Define a custom CreateTopicPolicy (cf. KIP-108 and the setting create.topic.policy.class.name) to enforce strict naming patterns. These policies provide the most flexibility and can cover complex patterns and rules to match an organization’s needs.
  • Disable topic creation for normal users by denying it with an ACL, and then rely on an external process to create topics on behalf of users (e.g., scripting or your favorite automation toolkit).
  • It may also be useful to disable the Kafka feature to auto-create topics on demand by setting auto.create.topics.enable=false in the broker configuration. Note that you should not rely solely on this option.

Kafka’s configuration is very flexible due to its fine granularity, and it supports a plethora of per-topic configuration settings to help administrators set up multi-tenant clusters. For example, administrators often need to define data retention policies to control how much and/or for how long data will be stored in a topic, with settings such as retention.bytes (size) and retention.ms (time). This limits storage consumption within the cluster, and helps complying with legal requirements such as GDPR.

Because the documentation has a dedicated chapter on security that applies to any Kafka deployment, this section focuses on additional considerations for multi-tenant environments.

Security settings for Kafka fall into three main categories, which are similar to how administrators would secure other client-server data systems, like relational databases and traditional messaging systems.

  1. Encryption of data transferred between Kafka brokers and Kafka clients, between brokers, between brokers and ZooKeeper nodes, and between brokers and other, optional tools.
  2. Authentication of connections from Kafka clients and applications to Kafka brokers, as well as connections from Kafka brokers to ZooKeeper nodes.
  3. Authorization of client operations such as creating, deleting, and altering the configuration of topics; writing events to or reading events from a topic; creating and deleting ACLs. Administrators can also define custom policies to put in place additional restrictions, such as a CreateTopicPolicy and AlterConfigPolicy (see KIP-108 and the settings create.topic.policy.class.name, alter.config.policy.class.name).

When securing a multi-tenant Kafka environment, the most common administrative task is the third category (authorization), i.e., managing the user/client permissions that grant or deny access to certain topics and thus to the data stored by users within a cluster. This task is performed predominantly through the setting of access control lists (ACLs). Here, administrators of multi-tenant environments in particular benefit from putting a hierarchical topic naming structure in place as described in a previous section, because they can conveniently control access to topics through prefixed ACLs (--resource-pattern-type Prefixed). This significantly minimizes the administrative overhead of securing topics in multi-tenant environments: administrators can make their own trade-offs between higher developer convenience (more lenient permissions, using fewer and broader ACLs) vs. tighter security (more stringent permissions, using more and narrower ACLs).

In the following example, user Alice—a new member of ACME corporation’s InfoSec team—is granted write permissions to all topics whose names start with “acme.infosec.”, such as “acme.infosec.telemetry.logins” and “acme.infosec.syslogs.events”.

# Grant permissions to user Alice
$ bin/kafka-acls.sh \
    --bootstrap-server broker1:9092 \
    --add --allow-principal User:Alice \
    --producer \
    --resource-pattern-type prefixed --topic acme.infosec.

You can similarly use this approach to isolate different customers on the same shared cluster.

Multi-tenant clusters should generally be configured with quotas, which protect against users (tenants) eating up too many cluster resources, such as when they attempt to write or read very high volumes of data, or create requests to brokers at an excessively high rate. This may cause network saturation, monopolize broker resources, and impact other clients—all of which you want to avoid in a shared environment.

Client quotas: Kafka supports different types of (per-user principal) client quotas. Because a client’s quotas apply irrespective of which topics the client is writing to or reading from, they are a convenient and effective tool to allocate resources in a multi-tenant cluster. Request rate quotas, for example, help to limit a user’s impact on broker CPU usage by limiting the time a broker spends on the request handling path for that user, after which throttling kicks in. In many situations, isolating users with request rate quotas has a bigger impact in multi-tenant clusters than setting incoming/outgoing network bandwidth quotas, because excessive broker CPU usage for processing requests reduces the effective bandwidth the broker can serve. Furthermore, administrators can also define quotas on topic operations—such as create, delete, and alter—to prevent Kafka clusters from being overwhelmed by highly concurrent topic operations (see KIP-599 and the quota type controller_mutations_rate).

Server quotas: Kafka also supports different types of broker-side quotas. For example, administrators can set a limit on the rate with which the broker accepts new connections, set the maximum number of connections per broker, or set the maximum number of connections allowed from a specific IP address.

For more information, please refer to the quota overview and how to set quotas.

Monitoring is a broader subject that is covered elsewhere in the documentation. Administrators of any Kafka environment, but especially multi-tenant ones, should set up monitoring according to these instructions. Kafka supports a wide range of metrics, such as the rate of failed authentication attempts, request latency, consumer lag, total number of consumer groups, metrics on the quotas described in the previous section, and many more.

For example, monitoring can be configured to track the size of topic-partitions (with the JMX metric kafka.log.Log.Size.<TOPIC-NAME>), and thus the total size of data stored in a topic. You can then define alerts when tenants on shared clusters are getting close to using too much storage space.

Kafka lets you share data across different clusters, which may be located in different geographical regions, data centers, and so on. Apart from use cases such as disaster recovery, this functionality is useful when a multi-tenant setup requires inter-cluster data sharing. See the section Geo-Replication (Cross-Cluster Data Mirroring) for more information.

Data contracts: You may need to define data contracts between the producers and the consumers of data in a cluster, using event schemas. This ensures that events written to Kafka can always be read properly again, and prevents malformed or corrupt events being written. The best way to achieve this is to deploy a so-called schema registry alongside the cluster. (Kafka does not include a schema registry, but there are third-party implementations available.) A schema registry manages the event schemas and maps the schemas to topics, so that producers know which topics are accepting which types (schemas) of events, and consumers know how to read and parse events in a topic. Some registry implementations provide further functionality, such as schema evolution, storing a history of all schemas, and schema compatibility settings.

The most important producer configurations are:

  • acks
  • compression
  • batch size

The most important consumer configuration is the fetch size.

The most important producer configurations are:The most important consumer configuration is the fetch size.

All configurations are documented in the configuration section.

Here is an example production server configuration:

  # ZooKeeper
  zookeeper.connect=[list of ZooKeeper servers]

  # Log configuration
  num.partitions=8
  default.replication.factor=3
  log.dir=[List of directories. Kafka should have its own dedicated disk(s) or SSD(s).]

  # Other configurations
  broker.id=[An integer. Start with 0 and increment by 1 for each new broker.]
  listeners=[list of listeners]
  auto.create.topics.enable=false
  min.insync.replicas=2
  queued.max.requests=[number of concurrent requests]

Our client configuration varies a fair amount between different use cases.

Java 8 and Java 11 are supported. Java 11 performs significantly better if TLS is enabled, so it is highly recommended (it also includes a number of other
performance improvements: G1GC, CRC32C, Compact Strings, Thread-Local Handshakes and more).

From a security perspective, we recommend the latest released patch version as older freely available versions have disclosed security vulnerabilities.

Typical arguments for running Kafka with OpenJDK-based Java implementations (including Oracle JDK) are:

  -Xmx6g -Xms6g -XX:MetaspaceSize=96m -XX:+UseG1GC
  -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M
  -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80 -XX:+ExplicitGCInvokesConcurrent

For reference, here are the stats for one of LinkedIn’s busiest clusters (at peak) that uses said Java arguments:

  • 60 brokers
  • 50k partitions (replication factor 2)
  • 800k messages/sec in
  • 300 MB/sec inbound, 1 GB/sec+ outbound

All of the brokers in that cluster have a 90% GC pause time of about 21ms with less than 1 young GC per second.

We are using dual quad-core Intel Xeon machines with 24GB of memory.

Here is an example production server configuration:Our client configuration varies a fair amount between different use cases.Java 8 and Java 11 are supported. Java 11 performs significantly better if TLS is enabled, so it is highly recommended (it also includes a number of other performance improvements: G1GC, CRC32C, Compact Strings, Thread-Local Handshakes and more). From a security perspective, we recommend the latest released patch version as older freely available versions have disclosed security vulnerabilities. Typical arguments for running Kafka with OpenJDK-based Java implementations (including Oracle JDK) are:For reference, here are the stats for one of LinkedIn’s busiest clusters (at peak) that uses said Java arguments:All of the brokers in that cluster have a 90% GC pause time of about 21ms with less than 1 young GC per second.We are using dual quad-core Intel Xeon machines with 24GB of memory.

You need sufficient memory to buffer active readers and writers. You can do a back-of-the-envelope estimate of memory needs by assuming you want to be able to buffer for 30 seconds and compute your memory need as write_throughput*30.

The disk throughput is important. We have 8×7200 rpm SATA drives. In general disk throughput is the performance bottleneck, and more disks is better. Depending on how you configure flush behavior you may or may not benefit from more expensive disks (if you force flush often then higher RPM SAS drives may be better).

Kafka should run well on any unix system and has been tested on Linux and Solaris.

Kafka should run well on any unix system and has been tested on Linux and Solaris.

We have seen a few issues running on Windows and Windows is not currently a well supported platform though we would be happy to change that.

It is unlikely to require much OS-level tuning, but there are three potentially important OS-level configurations:

  • File descriptor limits: Kafka uses file descriptors for log segments and open connections. If a broker hosts many partitions, consider that the broker needs at least (number_of_partitions)*(partition_size/segment_size) to track all log segments in addition to the number of connections the broker makes. We recommend at least 100000 allowed file descriptors for the broker processes as a starting point. Note: The mmap() function adds an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference is removed when there are no more mappings to the file.
  • Max socket buffer size: can be increased to enable high-performance data transfer between data centers as described here.
  • Maximum number of memory map areas a process may have (aka vm.max_map_count). See the Linux kernel documentation. You should keep an eye at this OS-level property when considering the maximum number of partitions a broker may have. By default, on a number of Linux systems, the value of vm.max_map_count is somewhere around 65535. Each log segment, allocated per partition, requires a pair of index/timeindex files, and each of these files consumes 1 map area. In other words, each log segment uses 2 map areas. Thus, each partition requires minimum 2 map areas, as long as it hosts a single log segment. That is to say, creating 50000 partitions on a broker will result allocation of 100000 map areas and likely cause broker crash with OutOfMemoryError (Map failed) on a system with default vm.max_map_count. Keep in mind that the number of log segments per partition varies depending on the segment size, load intensity, retention policy and, generally, tends to be more than one.

We recommend using multiple drives to get good throughput and not sharing the same drives used for Kafka data with application logs or other OS filesystem activity to ensure good latency. You can either RAID these drives together into a single volume or format and mount each drive as its own directory. Since Kafka has replication the redundancy provided by RAID can also be provided at the application level. This choice has several tradeoffs.

We recommend using multiple drives to get good throughput and not sharing the same drives used for Kafka data with application logs or other OS filesystem activity to ensure good latency. You can either RAID these drives together into a single volume or format and mount each drive as its own directory. Since Kafka has replication the redundancy provided by RAID can also be provided at the application level. This choice has several tradeoffs.

If you configure multiple data directories partitions will be assigned round-robin to data directories. Each partition will be entirely in one of the data directories. If data is not well balanced among partitions this can lead to load imbalance between disks.

RAID can potentially do better at balancing load between disks (although it doesn’t always seem to) because it balances load at a lower level. The primary downside of RAID is that it is usually a big performance hit for write throughput and reduces the available disk space.

Another potential benefit of RAID is the ability to tolerate disk failures. However our experience has been that rebuilding the RAID array is so I/O intensive that it effectively disables the server, so this does not provide much real availability improvement.

Kafka always immediately writes all data to the filesystem and supports the ability to configure the flush policy that controls when data is forced out of the OS cache and onto disk using the flush. This flush policy can be controlled to force data to disk after a period of time or after a certain number of messages has been written. There are several choices in this configuration.

Kafka always immediately writes all data to the filesystem and supports the ability to configure the flush policy that controls when data is forced out of the OS cache and onto disk using the flush. This flush policy can be controlled to force data to disk after a period of time or after a certain number of messages has been written. There are several choices in this configuration.

Kafka must eventually call fsync to know that data was flushed. When recovering from a crash for any log segment not known to be fsync’d Kafka will check the integrity of each message by checking its CRC and also rebuild the accompanying offset index file as part of the recovery process executed on startup.

Note that durability in Kafka does not require syncing data to disk, as a failed node will always recover from its replicas.

We recommend using the default flush settings which disable application fsync entirely. This means relying on the background flush done by the OS and Kafka’s own background flush. This provides the best of all worlds for most uses: no knobs to tune, great throughput and latency, and full recovery guarantees. We generally feel that the guarantees provided by replication are stronger than sync to local disk, however the paranoid still may prefer having both and application level fsync policies are still supported.

The drawback of using application level flush settings is that it is less efficient in its disk usage pattern (it gives the OS less leeway to re-order writes) and it can introduce latency as fsync in most Linux filesystems blocks writes to the file whereas the background flushing does much more granular page-level locking.

In general you don’t need to do any low-level tuning of the filesystem, but in the next few sections we will go over some of this in case it is useful.

In Linux, data written to the filesystem is maintained in

In Linux, data written to the filesystem is maintained in pagecache until it must be written out to disk (due to an application-level fsync or the OS’s own flush policy). The flushing of data is done by a set of background threads called pdflush (or in post 2.6.32 kernels “flusher threads”).

Pdflush has a configurable policy that controls how much dirty data can be maintained in cache and for how long before it must be written back to disk.
This policy is described here.
When Pdflush cannot keep up with the rate of data being written it will eventually cause the writing process to block incurring latency in the writes to slow down the accumulation of data.

You can see the current state of OS memory usage by doing

 > cat /proc/meminfo 

The meaning of these values are described in the link above.

The meaning of these values are described in the link above.

Using pagecache has several advantages over an in-process cache for storing data that will be written out to disk:

  • The I/O scheduler will batch together consecutive small writes into bigger physical writes which improves throughput.
  • The I/O scheduler will attempt to re-sequence writes to minimize movement of the disk head which improves throughput.
  • It automatically uses all the free memory on the machine

Kafka uses regular files on disk, and as such it has no hard dependency on a specific filesystem. The two filesystems which have the most usage, however, are EXT4 and XFS. Historically, EXT4 has had more usage, but recent improvements to the XFS filesystem have shown it to have better performance characteristics for Kafka’s workload with no compromise in stability.

Comparison testing was performed on a cluster with significant message loads, using a variety of filesystem creation and mount options. The primary metric in Kafka that was monitored was the “Request Local Time”, indicating the amount of time append operations were taking. XFS resulted in much better local times (160ms vs. 250ms+ for the best EXT4 configuration), as well as lower average wait times. The XFS performance also showed less variability in disk performance.

For any filesystem used for data directories, on Linux systems, the following options are recommended to be used at mount time:

  • noatime: This option disables updating of a file’s atime (last access time) attribute when the file is read. This can eliminate a significant number of filesystem writes, especially in the case of bootstrapping consumers. Kafka does not rely on the atime attributes at all, so it is safe to disable this.

The XFS filesystem has a significant amount of auto-tuning in place, so it does not require any change in the default settings, either at filesystem creation time or at mount. The only tuning parameters worth considering are:

  • largeio: This affects the preferred I/O size reported by the stat call. While this can allow for higher performance on larger disk writes, in practice it had minimal or no effect on performance.
  • nobarrier: For underlying devices that have battery-backed cache, this option can provide a little more performance by disabling periodic write flushes. However, if the underlying device is well-behaved, it will report to the filesystem that it does not require flushes, and this option will have no effect.

EXT4 is a serviceable choice of filesystem for the Kafka data directories, however getting the most performance out of it will require adjusting several mount options. In addition, these options are generally unsafe in a failure scenario, and will result in much more data loss and corruption. For a single broker failure, this is not much of a concern as the disk can be wiped and the replicas rebuilt from the cluster. In a multiple-failure scenario, such as a power outage, this can mean underlying filesystem (and therefore data) corruption that is not easily recoverable. The following options can be adjusted:

  • data=writeback: Ext4 defaults to data=ordered which puts a strong order on some writes. Kafka does not require this ordering as it does very paranoid data recovery on all unflushed log. This setting removes the ordering constraint and seems to significantly reduce latency.
  • Disabling journaling: Journaling is a tradeoff: it makes reboots faster after server crashes but it introduces a great deal of additional locking which adds variance to write performance. Those who don’t care about reboot time and want to reduce a major source of write latency spikes can turn off journaling entirely.
  • commit=num_secs: This tunes the frequency with which ext4 commits to its metadata journal. Setting this to a lower value reduces the loss of unflushed data during a crash. Setting this to a higher value will improve throughput.
  • nobh: This setting controls additional ordering guarantees when using data=writeback mode. This should be safe with Kafka as we do not depend on write ordering and improves throughput and latency.
  • delalloc: Delayed allocation means that the filesystem avoid allocating any blocks until the physical write occurs. This allows ext4 to allocate a large extent instead of smaller pages and helps ensure the data is written sequentially. This feature is great for throughput. It does seem to involve some locking in the filesystem which adds a bit of latency variance.

Kafka uses Yammer Metrics for metrics reporting in the server. The Java clients use Kafka Metrics, a built-in metrics registry that minimizes transitive dependencies pulled into client applications. Both expose metrics via JMX and can be configured to report stats using pluggable stats reporters to hook up to your monitoring system.

For any filesystem used for data directories, on Linux systems, the following options are recommended to be used at mount time:The XFS filesystem has a significant amount of auto-tuning in place, so it does not require any change in the default settings, either at filesystem creation time or at mount. The only tuning parameters worth considering are:EXT4 is a serviceable choice of filesystem for the Kafka data directories, however getting the most performance out of it will require adjusting several mount options. In addition, these options are generally unsafe in a failure scenario, and will result in much more data loss and corruption. For a single broker failure, this is not much of a concern as the disk can be wiped and the replicas rebuilt from the cluster. In a multiple-failure scenario, such as a power outage, this can mean underlying filesystem (and therefore data) corruption that is not easily recoverable. The following options can be adjusted:Kafka uses Yammer Metrics for metrics reporting in the server. The Java clients use Kafka Metrics, a built-in metrics registry that minimizes transitive dependencies pulled into client applications. Both expose metrics via JMX and can be configured to report stats using pluggable stats reporters to hook up to your monitoring system.

All Kafka rate metrics have a corresponding cumulative count metric with suffix -total. For example,
records-consumed-rate has a corresponding metric named records-consumed-total.

The easiest way to see the available metrics is to fire up jconsole and point it at a running kafka client or server; this will allow browsing all metrics with JMX.

Apache Kafka disables remote JMX by default. You can enable remote monitoring using JMX by setting the environment variable
JMX_PORT for processes started using the CLI or standard Java system properties to enable remote JMX programmatically.
You must enable security when enabling remote JMX in production scenarios to ensure that unauthorized users cannot monitor or
control your broker or application as well as the platform on which these are running. Note that authentication is disabled for
JMX by default in Kafka and security configs must be overridden for production deployments by setting the environment variable
KAFKA_JMX_OPTS for processes started using the CLI or by setting appropriate Java system properties. See

Apache Kafka disables remote JMX by default. You can enable remote monitoring using JMX by setting the environment variablefor processes started using the CLI or standard Java system properties to enable remote JMX programmatically. You must enable security when enabling remote JMX in production scenarios to ensure that unauthorized users cannot monitor or control your broker or application as well as the platform on which these are running. Note that authentication is disabled for JMX by default in Kafka and security configs must be overridden for production deployments by setting the environment variablefor processes started using the CLI or by setting appropriate Java system properties. See Monitoring and Management Using JMX Technology for details on securing JMX.

We do graphing and alerting on the following metrics:

Description
Mbean name
Normal value

Message in rate
kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec

Byte in rate from clients
kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec

Byte in rate from other brokers
kafka.server:type=BrokerTopicMetrics,name=ReplicationBytesInPerSec

Controller Request rate from Broker
kafka.controller:type=ControllerChannelManager,name=RequestRateAndQueueTimeMs,brokerId=([0-9]+)
The rate (requests per second) at which the ControllerChannelManager takes requests from the
queue of the given broker. And the time it takes for a request to stay in this queue before
it is taken from the queue.

Controller Event queue size
kafka.controller:type=ControllerEventManager,name=EventQueueSize
Size of the ControllerEventManager’s queue.

Controller Event queue time
kafka.controller:type=ControllerEventManager,name=EventQueueTimeMs
Time that takes for any event (except the Idle event) to wait in the ControllerEventManager’s
queue before being processed

Request rate
kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower},version=([0-9]+)

Error rate
kafka.network:type=RequestMetrics,name=ErrorsPerSec,request=([-.\w]+),error=([-.\w]+)
Number of errors in responses counted per-request-type, per-error-code. If a response contains
multiple errors, all are counted. error=NONE indicates successful responses.

Request size in bytes
kafka.network:type=RequestMetrics,name=RequestBytes,request=([-.\w]+)
Size of requests for each request type.

Temporary memory size in bytes
kafka.network:type=RequestMetrics,name=TemporaryMemoryBytes,request={Produce|Fetch}
Temporary memory used for message format conversions and decompression.

Message conversion time
kafka.network:type=RequestMetrics,name=MessageConversionsTimeMs,request={Produce|Fetch}
Time in milliseconds spent on message format conversions.

Message conversion rate
kafka.server:type=BrokerTopicMetrics,name={Produce|Fetch}MessageConversionsPerSec,topic=([-.\w]+)
Number of records which required message format conversion.

Request Queue Size
kafka.network:type=RequestChannel,name=RequestQueueSize
Size of the request queue.

Byte out rate to clients
kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec

Byte out rate to other brokers
kafka.server:type=BrokerTopicMetrics,name=ReplicationBytesOutPerSec

Message validation failure rate due to no key specified for compacted topic
kafka.server:type=BrokerTopicMetrics,name=NoKeyCompactedTopicRecordsPerSec

Message validation failure rate due to invalid magic number
kafka.server:type=BrokerTopicMetrics,name=InvalidMagicNumberRecordsPerSec

Message validation failure rate due to incorrect crc checksum
kafka.server:type=BrokerTopicMetrics,name=InvalidMessageCrcRecordsPerSec

Message validation failure rate due to non-continuous offset or sequence number in batch
kafka.server:type=BrokerTopicMetrics,name=InvalidOffsetOrSequenceRecordsPerSec

Log flush rate and time
kafka.log:type=LogFlushStats,name=LogFlushRateAndTimeMs

# of offline log directories
kafka.log:type=LogManager,name=OfflineLogDirectoryCount
0

Leader election rate
kafka.controller:type=ControllerStats,name=LeaderElectionRateAndTimeMs
non-zero when there are broker failures

Unclean leader election rate
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec
0

Is controller active on broker
kafka.controller:type=KafkaController,name=ActiveControllerCount
only one broker in the cluster should have 1

Pending topic deletes
kafka.controller:type=KafkaController,name=TopicsToDeleteCount

Pending replica deletes
kafka.controller:type=KafkaController,name=ReplicasToDeleteCount

Ineligible pending topic deletes
kafka.controller:type=KafkaController,name=TopicsIneligibleToDeleteCount

Ineligible pending replica deletes
kafka.controller:type=KafkaController,name=ReplicasIneligibleToDeleteCount

# of under replicated partitions (|ISR| &lt |all replicas|)
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions
0

# of under minIsr partitions (|ISR| &lt min.insync.replicas)
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount
0

# of at minIsr partitions (|ISR| = min.insync.replicas)
kafka.server:type=ReplicaManager,name=AtMinIsrPartitionCount
0

Partition counts
kafka.server:type=ReplicaManager,name=PartitionCount
mostly even across brokers

Offline Replica counts
kafka.server:type=ReplicaManager,name=OfflineReplicaCount
0

Leader replica counts
kafka.server:type=ReplicaManager,name=LeaderCount
mostly even across brokers

ISR shrink rate
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec
If a broker goes down, ISR for some of the partitions will
shrink. When that broker is up again, ISR will be expanded
once the replicas are fully caught up. Other than that, the
expected value for both ISR shrink rate and expansion rate is 0.

ISR expansion rate
kafka.server:type=ReplicaManager,name=IsrExpandsPerSec
See above

Failed ISR update rate
kafka.server:type=ReplicaManager,name=FailedIsrUpdatesPerSec
0

Max lag in messages btw follower and leader replicas
kafka.server:type=ReplicaFetcherManager,name=MaxLag,clientId=Replica
lag should be proportional to the maximum batch size of a produce request.

Lag in messages per follower replica
kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+)
lag should be proportional to the maximum batch size of a produce request.

Requests waiting in the producer purgatory
kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Produce
non-zero if ack=-1 is used

Requests waiting in the fetch purgatory
kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Fetch
size depends on fetch.wait.max.ms in the consumer

Request total time
kafka.network:type=RequestMetrics,name=TotalTimeMs,request={Produce|FetchConsumer|FetchFollower}
broken into queue, local, remote and response send time

Time the request waits in the request queue
kafka.network:type=RequestMetrics,name=RequestQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}

Time the request is processed at the leader
kafka.network:type=RequestMetrics,name=LocalTimeMs,request={Produce|FetchConsumer|FetchFollower}

Time the request waits for the follower
kafka.network:type=RequestMetrics,name=RemoteTimeMs,request={Produce|FetchConsumer|FetchFollower}
non-zero for produce requests when ack=-1

Time the request waits in the response queue
kafka.network:type=RequestMetrics,name=ResponseQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}

Time to send the response
kafka.network:type=RequestMetrics,name=ResponseSendTimeMs,request={Produce|FetchConsumer|FetchFollower}

Number of messages the consumer lags behind the producer by. Published by the consumer, not broker.
kafka.consumer:type=consumer-fetch-manager-metrics,client-id={client-id} Attribute: records-lag-max

The average fraction of time the network processors are idle
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent
between 0 and 1, ideally &gt 0.3

The number of connections disconnected on a processor due to a client not re-authenticating and then using the connection beyond its expiration time for anything other than re-authentication
kafka.server:type=socket-server-metrics,listener=[SASL_PLAINTEXT|SASL_SSL],networkProcessor=<#>,name=expired-connections-killed-count
ideally 0 when re-authentication is enabled, implying there are no longer any older, pre-2.2.0 clients connecting to this (listener, processor) combination

The total number of connections disconnected, across all processors, due to a client not re-authenticating and then using the connection beyond its expiration time for anything other than re-authentication
kafka.network:type=SocketServer,name=ExpiredConnectionsKilledCount
ideally 0 when re-authentication is enabled, implying there are no longer any older, pre-2.2.0 clients connecting to this broker

The average fraction of time the request handler threads are idle
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent
between 0 and 1, ideally &gt 0.3

Bandwidth quota metrics per (user, client-id), user or client-id
kafka.server:type={Produce|Fetch},user=([-.\w]+),client-id=([-.\w]+)
Two attributes. throttle-time indicates the amount of time in ms the client was throttled. Ideally = 0.
byte-rate indicates the data produce/consume rate of the client in bytes/sec.
For (user, client-id) quotas, both user and client-id are specified. If per-client-id quota is applied to the client, user is not specified. If per-user quota is applied, client-id is not specified.

Request quota metrics per (user, client-id), user or client-id
kafka.server:type=Request,user=([-.\w]+),client-id=([-.\w]+)
Two attributes. throttle-time indicates the amount of time in ms the client was throttled. Ideally = 0.
request-time indicates the percentage of time spent in broker network and I/O threads to process requests from client group.
For (user, client-id) quotas, both user and client-id are specified. If per-client-id quota is applied to the client, user is not specified. If per-user quota is applied, client-id is not specified.

Requests exempt from throttling
kafka.server:type=Request
exempt-throttle-time indicates the percentage of time spent in broker network and I/O threads to process requests
that are exempt from throttling.

ZooKeeper client request latency
kafka.server:type=ZooKeeperClientMetrics,name=ZooKeeperRequestLatencyMs
Latency in millseconds for ZooKeeper requests from broker.

ZooKeeper connection status
kafka.server:type=SessionExpireListener,name=SessionState
Connection status of broker’s ZooKeeper session which may be one of
Disconnected|SyncConnected|AuthFailed|ConnectedReadOnly|SaslAuthenticated|Expired.

Max time to load group metadata
kafka.server:type=group-coordinator-metrics,name=partition-load-time-max
maximum time, in milliseconds, it took to load offsets and group metadata from the consumer offset partitions loaded in the last 30 seconds (including time spent waiting for the loading task to be scheduled)

Avg time to load group metadata
kafka.server:type=group-coordinator-metrics,name=partition-load-time-avg
average time, in milliseconds, it took to load offsets and group metadata from the consumer offset partitions loaded in the last 30 seconds (including time spent waiting for the loading task to be scheduled)

Max time to load transaction metadata
kafka.server:type=transaction-coordinator-metrics,name=partition-load-time-max
maximum time, in milliseconds, it took to load transaction metadata from the consumer offset partitions loaded in the last 30 seconds (including time spent waiting for the loading task to be scheduled)

Avg time to load transaction metadata
kafka.server:type=transaction-coordinator-metrics,name=partition-load-time-avg
average time, in milliseconds, it took to load transaction metadata from the consumer offset partitions loaded in the last 30 seconds (including time spent waiting for the loading task to be scheduled)

Consumer Group Offset Count
kafka.server:type=GroupMetadataManager,name=NumOffsets
Total number of committed offsets for Consumer Groups

Consumer Group Count
kafka.server:type=GroupMetadataManager,name=NumGroups
Total number of Consumer Groups

Consumer Group Count, per State
kafka.server:type=GroupMetadataManager,name=NumGroups[PreparingRebalance,CompletingRebalance,Empty,Stable,Dead]
The number of Consumer Groups in each state: PreparingRebalance, CompletingRebalance, Empty, Stable, Dead

Number of reassigning partitions
kafka.server:type=ReplicaManager,name=ReassigningPartitions
The number of reassigning leader partitions on a broker.

Outgoing byte rate of reassignment traffic
kafka.server:type=BrokerTopicMetrics,name=ReassignmentBytesOutPerSec

Incoming byte rate of reassignment traffic
kafka.server:type=BrokerTopicMetrics,name=ReassignmentBytesInPerSec

Size of a partition on disk (in bytes)
kafka.log:type=Log,name=Size,topic=([-.\w]+),partition=([0-9]+)
The size of a partition on disk, measured in bytes.

Number of log segments in a partition
kafka.log:type=Log,name=NumLogSegments,topic=([-.\w]+),partition=([0-9]+)
The number of log segments in a partition.

First offset in a partition
kafka.log:type=Log,name=LogStartOffset,topic=([-.\w]+),partition=([0-9]+)
The first offset in a partition.

Last offset in a partition
kafka.log:type=Log,name=LogEndOffset,topic=([-.\w]+),partition=([0-9]+)
The last offset in a partition.

The following metrics are available on producer/consumer/connector/streams instances. For specific metrics, please see following sections.

Metric/Attribute name
Description
Mbean name

connection-close-rate
Connections closed per second in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

connection-close-total
Total connections closed in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

connection-creation-rate
New connections established per second in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

connection-creation-total
Total new connections established in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

network-io-rate
The average number of network operations (reads or writes) on all connections per second.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

network-io-total
The total number of network operations (reads or writes) on all connections.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

outgoing-byte-rate
The average number of outgoing bytes sent per second to all servers.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

outgoing-byte-total
The total number of outgoing bytes sent to all servers.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

request-rate
The average number of requests sent per second.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

request-total
The total number of requests sent.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

request-size-avg
The average size of all requests in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

request-size-max
The maximum size of any request sent in the window.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

incoming-byte-rate
Bytes/second read off all sockets.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

incoming-byte-total
Total bytes read off all sockets.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

response-rate
Responses received per second.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

response-total
Total responses received.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

select-rate
Number of times the I/O layer checked for new I/O to perform per second.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

select-total
Total number of times the I/O layer checked for new I/O to perform.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

io-wait-time-ns-avg
The average length of time the I/O thread spent waiting for a socket ready for reads or writes in nanoseconds.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

io-wait-ratio
The fraction of time the I/O thread spent waiting.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

io-time-ns-avg
The average length of time for I/O per select call in nanoseconds.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

io-ratio
The fraction of time the I/O thread spent doing I/O.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

connection-count
The current number of active connections.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

successful-authentication-rate
Connections per second that were successfully authenticated using SASL or SSL.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

successful-authentication-total
Total connections that were successfully authenticated using SASL or SSL.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

failed-authentication-rate
Connections per second that failed authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

failed-authentication-total
Total connections that failed authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

successful-reauthentication-rate
Connections per second that were successfully re-authenticated using SASL.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

successful-reauthentication-total
Total connections that were successfully re-authenticated using SASL.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

reauthentication-latency-max
The maximum latency in ms observed due to re-authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

reauthentication-latency-avg
The average latency in ms observed due to re-authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

failed-reauthentication-rate
Connections per second that failed re-authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

failed-reauthentication-total
Total connections that failed re-authentication.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

successful-authentication-no-reauth-total
Total connections that were successfully authenticated by older, pre-2.2.0 SASL clients that do not support re-authentication. May only be non-zero.
kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

The following metrics are available on producer/consumer/connector/streams instances. For specific metrics, please see following sections.

Metric/Attribute name
Description
Mbean name

outgoing-byte-rate
The average number of outgoing bytes sent per second for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

outgoing-byte-total
The total number of outgoing bytes sent for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-rate
The average number of requests sent per second for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-total
The total number of requests sent for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-size-avg
The average size of all requests in the window for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-size-max
The maximum size of any request sent in the window for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

incoming-byte-rate
The average number of bytes received per second for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

incoming-byte-total
The total number of bytes received for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-latency-avg
The average request latency in ms for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

request-latency-max
The maximum request latency in ms for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

response-rate
Responses received per second for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

response-total
Total responses received for a node.
kafka.[producer|consumer|connect]:type=[consumer|producer|connect]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

The following metrics are available on producer instances.

Metric/Attribute name
Description
Mbean name

waiting-threads
The number of user threads blocked waiting for buffer memory to enqueue their records.
kafka.producer:type=producer-metrics,client-id=([-.\w]+)

buffer-total-bytes
The maximum amount of buffer memory the client can use (whether or not it is currently used).
kafka.producer:type=producer-metrics,client-id=([-.\w]+)

buffer-available-bytes
The total amount of buffer memory that is not being used (either unallocated or in the free list).
kafka.producer:type=producer-metrics,client-id=([-.\w]+)

bufferpool-wait-time
The fraction of time an appender waits for space allocation.
kafka.producer:type=producer-metrics,client-id=([-.\w]+)

kafka.producer:type=producer-metrics,client-id=”{client-id}”

Attribute name
Description

batch-size-avgThe average number of bytes sent per partition per-request.

batch-size-maxThe max number of bytes sent per partition per-request.

batch-split-rateThe average number of batch splits per second

batch-split-totalThe total number of batch splits

compression-rate-avgThe average compression rate of record batches, defined as the average ratio of the compressed batch size over the uncompressed size.

metadata-ageThe age in seconds of the current producer metadata being used.

produce-throttle-time-avgThe average time in ms a request was throttled by a broker

produce-throttle-time-maxThe maximum time in ms a request was throttled by a broker

record-error-rateThe average per-second number of record sends that resulted in errors

record-error-totalThe total number of record sends that resulted in errors

record-queue-time-avgThe average time in ms record batches spent in the send buffer.

record-queue-time-maxThe maximum time in ms record batches spent in the send buffer.

record-retry-rateThe average per-second number of retried record sends

record-retry-totalThe total number of retried record sends

record-send-rateThe average number of records sent per second.

record-send-totalThe total number of records sent.

record-size-avgThe average record size

record-size-maxThe maximum record size

records-per-request-avgThe average number of records per request.

request-latency-avgThe average request latency in ms

request-latency-maxThe maximum request latency in ms

requests-in-flightThe current number of in-flight requests awaiting a response.

kafka.producer:type=producer-topic-metrics,client-id=”{client-id}”,topic=”{topic}”

Attribute name
Description

byte-rateThe average number of bytes sent per second for a topic.

byte-totalThe total number of bytes sent for a topic.

compression-rateThe average compression rate of record batches for a topic, defined as the average ratio of the compressed batch size over the uncompressed size.

record-error-rateThe average per-second number of record sends that resulted in errors for a topic

record-error-totalThe total number of record sends that resulted in errors for a topic

record-retry-rateThe average per-second number of retried record sends for a topic

record-retry-totalThe total number of retried record sends for a topic

record-send-rateThe average number of records sent per second for a topic.

record-send-totalThe total number of records sent for a topic.

The following metrics are available on consumer instances.

Metric/Attribute name
Description
Mbean name

time-between-poll-avg
The average delay between invocations of poll().
kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)

time-between-poll-max
The max delay between invocations of poll().
kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)

last-poll-seconds-ago
The number of seconds since the last poll() invocation.
kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)

poll-idle-ratio-avg
The average fraction of time the consumer’s poll() is idle as opposed to waiting for the user code to process records.
kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)

Metric/Attribute name
Description
Mbean name

commit-latency-avg
The average time taken for a commit request
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

commit-latency-max
The max time taken for a commit request
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

commit-rate
The number of commit calls per second
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

commit-total
The total number of commit calls
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

assigned-partitions
The number of partitions currently assigned to this consumer
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

heartbeat-response-time-max
The max time taken to receive a response to a heartbeat request
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

heartbeat-rate
The average number of heartbeats per second
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

heartbeat-total
The total number of heartbeats
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

join-time-avg
The average time taken for a group rejoin
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

join-time-max
The max time taken for a group rejoin
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

join-rate
The number of group joins per second
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

join-total
The total number of group joins
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

sync-time-avg
The average time taken for a group sync
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

sync-time-max
The max time taken for a group sync
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

sync-rate
The number of group syncs per second
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

sync-total
The total number of group syncs
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

rebalance-latency-avg
The average time taken for a group rebalance
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

rebalance-latency-max
The max time taken for a group rebalance
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

rebalance-latency-total
The total time taken for group rebalances so far
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

rebalance-total
The total number of group rebalances participated
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

rebalance-rate-per-hour
The number of group rebalance participated per hour
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

failed-rebalance-total
The total number of failed group rebalances
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

failed-rebalance-rate-per-hour
The number of failed group rebalance event per hour
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

last-rebalance-seconds-ago
The number of seconds since the last rebalance event
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

last-heartbeat-seconds-ago
The number of seconds since the last controller heartbeat
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-revoked-latency-avg
The average time taken by the on-partitions-revoked rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-revoked-latency-max
The max time taken by the on-partitions-revoked rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-assigned-latency-avg
The average time taken by the on-partitions-assigned rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-assigned-latency-max
The max time taken by the on-partitions-assigned rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-lost-latency-avg
The average time taken by the on-partitions-lost rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

partitions-lost-latency-max
The max time taken by the on-partitions-lost rebalance listener callback
kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)

kafka.consumer:type=consumer-fetch-manager-metrics,client-id=”{client-id}”

Attribute name
Description

bytes-consumed-rateThe average number of bytes consumed per second

bytes-consumed-totalThe total number of bytes consumed

fetch-latency-avgThe average time taken for a fetch request.

fetch-latency-maxThe max time taken for any fetch request.

fetch-rateThe number of fetch requests per second.

fetch-size-avgThe average number of bytes fetched per request

fetch-size-maxThe maximum number of bytes fetched per request

fetch-throttle-time-avgThe average throttle time in ms

fetch-throttle-time-maxThe maximum throttle time in ms

fetch-totalThe total number of fetch requests.

records-consumed-rateThe average number of records consumed per second

records-consumed-totalThe total number of records consumed

records-lag-maxThe maximum lag in terms of number of records for any partition in this window

records-lead-minThe minimum lead in terms of number of records for any partition in this window

records-per-request-avgThe average number of records in each request

kafka.consumer:type=consumer-fetch-manager-metrics,client-id=”{client-id}”,topic=”{topic}”

Attribute name
Description

bytes-consumed-rateThe average number of bytes consumed per second for a topic

bytes-consumed-totalThe total number of bytes consumed for a topic

fetch-size-avgThe average number of bytes fetched per request for a topic

fetch-size-maxThe maximum number of bytes fetched per request for a topic

records-consumed-rateThe average number of records consumed per second for a topic

records-consumed-totalThe total number of records consumed for a topic

records-per-request-avgThe average number of records in each request for a topic

kafka.consumer:type=consumer-fetch-manager-metrics,partition=”{partition}”,topic=”{topic}”,client-id=”{client-id}”

Attribute name
Description

preferred-read-replicaThe current read replica for the partition, or -1 if reading from leader

records-lagThe latest lag of the partition

records-lag-avgThe average lag of the partition

records-lag-maxThe max lag of the partition

records-leadThe latest lead of the partition

records-lead-avgThe average lead of the partition

records-lead-minThe min lead of the partition

A Connect worker process contains all the producer and consumer metrics as well as metrics specific to Connect.
The worker process itself has a number of metrics, while each connector and task have additional metrics.

[2021-09-09 00:26:06,127] INFO Metrics scheduler closed (org.apache.kafka.common.metrics.Metrics:659)
[2021-09-09 00:26:06,131] INFO Metrics reporters closed (org.apache.kafka.common.metrics.Metrics:669)

kafka.connect:type=connect-worker-metrics

Attribute name
Description

connector-countThe number of connectors run in this worker.

connector-startup-attempts-totalThe total number of connector startups that this worker has attempted.

connector-startup-failure-percentageThe average percentage of this worker’s connectors starts that failed.

connector-startup-failure-totalThe total number of connector starts that failed.

connector-startup-success-percentageThe average percentage of this worker’s connectors starts that succeeded.

connector-startup-success-totalThe total number of connector starts that succeeded.

task-countThe number of tasks run in this worker.

task-startup-attempts-totalThe total number of task startups that this worker has attempted.

task-startup-failure-percentageThe average percentage of this worker’s tasks starts that failed.

task-startup-failure-totalThe total number of task starts that failed.

task-startup-success-percentageThe average percentage of this worker’s tasks starts that succeeded.

task-startup-success-totalThe total number of task starts that succeeded.

kafka.connect:type=connect-worker-metrics,connector=”{connector}”

Attribute name
Description

connector-destroyed-task-countThe number of destroyed tasks of the connector on the worker.

connector-failed-task-countThe number of failed tasks of the connector on the worker.

connector-paused-task-countThe number of paused tasks of the connector on the worker.

connector-restarting-task-countThe number of restarting tasks of the connector on the worker.

connector-running-task-countThe number of running tasks of the connector on the worker.

connector-total-task-countThe number of tasks of the connector on the worker.

connector-unassigned-task-countThe number of unassigned tasks of the connector on the worker.

kafka.connect:type=connect-worker-rebalance-metrics

Attribute name
Description

completed-rebalances-totalThe total number of rebalances completed by this worker.

connect-protocolThe Connect protocol used by this cluster

epochThe epoch or generation number of this worker.

leader-nameThe name of the group leader.

rebalance-avg-time-msThe average time in milliseconds spent by this worker to rebalance.

rebalance-max-time-msThe maximum time in milliseconds spent by this worker to rebalance.

rebalancingWhether this worker is currently rebalancing.

time-since-last-rebalance-msThe time in milliseconds since this worker completed the most recent rebalance.

kafka.connect:type=connector-metrics,connector=”{connector}”

Attribute name
Description

connector-classThe name of the connector class.

connector-typeThe type of the connector. One of ‘source’ or ‘sink’.

connector-versionThe version of the connector class, as reported by the connector.

statusThe status of the connector. One of ‘unassigned’, ‘running’, ‘paused’, ‘failed’, or ‘destroyed’.

kafka.connect:type=connector-task-metrics,connector=”{connector}”,task=”{task}”

Attribute name
Description

batch-size-avgThe average size of the batches processed by the connector.

batch-size-maxThe maximum size of the batches processed by the connector.

offset-commit-avg-time-msThe average time in milliseconds taken by this task to commit offsets.

offset-commit-failure-percentageThe average percentage of this task’s offset commit attempts that failed.

offset-commit-max-time-msThe maximum time in milliseconds taken by this task to commit offsets.

offset-commit-success-percentageThe average percentage of this task’s offset commit attempts that succeeded.

pause-ratioThe fraction of time this task has spent in the pause state.

running-ratioThe fraction of time this task has spent in the running state.

statusThe status of the connector task. One of ‘unassigned’, ‘running’, ‘paused’, ‘failed’, or ‘destroyed’.

kafka.connect:type=sink-task-metrics,connector=”{connector}”,task=”{task}”

Attribute name
Description

offset-commit-completion-rateThe average per-second number of offset commit completions that were completed successfully.

offset-commit-completion-totalThe total number of offset commit completions that were completed successfully.

offset-commit-seq-noThe current sequence number for offset commits.

offset-commit-skip-rateThe average per-second number of offset commit completions that were received too late and skipped/ignored.

offset-commit-skip-totalThe total number of offset commit completions that were received too late and skipped/ignored.

partition-countThe number of topic partitions assigned to this task belonging to the named sink connector in this worker.

put-batch-avg-time-msThe average time taken by this task to put a batch of sinks records.

put-batch-max-time-msThe maximum time taken by this task to put a batch of sinks records.

sink-record-active-countThe number of records that have been read from Kafka but not yet completely committed/flushed/acknowledged by the sink task.

sink-record-active-count-avgThe average number of records that have been read from Kafka but not yet completely committed/flushed/acknowledged by the sink task.

sink-record-active-count-maxThe maximum number of records that have been read from Kafka but not yet completely committed/flushed/acknowledged by the sink task.

sink-record-lag-maxThe maximum lag in terms of number of records that the sink task is behind the consumer’s position for any topic partitions.

sink-record-read-rateThe average per-second number of records read from Kafka for this task belonging to the named sink connector in this worker. This is before transformations are applied.

sink-record-read-totalThe total number of records read from Kafka by this task belonging to the named sink connector in this worker, since the task was last restarted.

sink-record-send-rateThe average per-second number of records output from the transformations and sent/put to this task belonging to the named sink connector in this worker. This is after transformations are applied and excludes any records filtered out by the transformations.

sink-record-send-totalThe total number of records output from the transformations and sent/put to this task belonging to the named sink connector in this worker, since the task was last restarted.

kafka.connect:type=source-task-metrics,connector=”{connector}”,task=”{task}”

Attribute name
Description

poll-batch-avg-time-msThe average time in milliseconds taken by this task to poll for a batch of source records.

poll-batch-max-time-msThe maximum time in milliseconds taken by this task to poll for a batch of source records.

source-record-active-countThe number of records that have been produced by this task but not yet completely written to Kafka.

source-record-active-count-avgThe average number of records that have been produced by this task but not yet completely written to Kafka.

source-record-active-count-maxThe maximum number of records that have been produced by this task but not yet completely written to Kafka.

source-record-poll-rateThe average per-second number of records produced/polled (before transformation) by this task belonging to the named source connector in this worker.

source-record-poll-totalThe total number of records produced/polled (before transformation) by this task belonging to the named source connector in this worker.

source-record-write-rateThe average per-second number of records output from the transformations and written to Kafka for this task belonging to the named source connector in this worker. This is after transformations are applied and excludes any records filtered out by the transformations.

source-record-write-totalThe number of records output from the transformations and written to Kafka for this task belonging to the named source connector in this worker, since the task was last restarted.

kafka.connect:type=task-error-metrics,connector=”{connector}”,task=”{task}”

Attribute name
Description

deadletterqueue-produce-failuresThe number of failed writes to the dead letter queue.

deadletterqueue-produce-requestsThe number of attempted writes to the dead letter queue.

last-error-timestampThe epoch timestamp when this task last encountered an error.

total-errors-loggedThe number of errors that were logged.

total-record-errorsThe number of record processing errors in this task.

total-record-failuresThe number of record processing failures in this task.

total-records-skippedThe number of records skipped due to errors.

total-retriesThe number of operations retried.

A Kafka Streams instance contains all the producer and consumer metrics as well as additional metrics specific to Streams.
By default Kafka Streams has metrics with three recording levels: info, debug, and trace.

The following metrics are available on producer/consumer/connector/streams instances. For specific metrics, please see following sections.The following metrics are available on producer/consumer/connector/streams instances. For specific metrics, please see following sections.The following metrics are available on producer instances.The following metrics are available on consumer instances.A Connect worker process contains all the producer and consumer metrics as well as metrics specific to Connect. The worker process itself has a number of metrics, while each connector and task have additional metrics. [2021-09-09 00:26:06,127] INFO Metrics scheduler closed (org.apache.kafka.common.metrics.Metrics:659) [2021-09-09 00:26:06,131] INFO Metrics reporters closed (org.apache.kafka.common.metrics.Metrics:669)A Kafka Streams instance contains all the producer and consumer metrics as well as additional metrics specific to Streams. By default Kafka Streams has metrics with three recording levels:, and

Note that the metrics have a 4-layer hierarchy. At the top level there are client-level metrics for each started
Kafka Streams client. Each client has stream threads, with their own metrics. Each stream thread has tasks, with their
own metrics. Each task has a number of processor nodes, with their own metrics. Each task also has a number of state stores
and record caches, all with their own metrics.

Use the following configuration option to specify which metrics
you want collected:

metrics.recording.level="info"

All of the following metrics have a recording level of info:

Metric/Attribute name
Description
Mbean name

version
The version of the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

commit-id
The version control commit ID of the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

application-id
The application ID of the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

topology-description
The description of the topology executed in the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

state
The state of the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

failed-stream-threads
The number of failed stream threads since the start of the Kafka Streams client.
kafka.streams:type=stream-metrics,client-id=([-.\w]+)

All of the following metrics have a recording level of info:

Metric/Attribute name
Description
Mbean name

commit-latency-avg
The average execution time in ms, for committing, across all running tasks of this thread.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

commit-latency-max
The maximum execution time in ms, for committing, across all running tasks of this thread.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

poll-latency-avg
The average execution time in ms, for consumer polling.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

poll-latency-max
The maximum execution time in ms, for consumer polling.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

process-latency-avg
The average execution time in ms, for processing.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

process-latency-max
The maximum execution time in ms, for processing.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

punctuate-latency-avg
The average execution time in ms, for punctuating.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

punctuate-latency-max
The maximum execution time in ms, for punctuating.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

commit-rate
The average number of commits per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

commit-total
The total number of commit calls.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

poll-rate
The average number of consumer poll calls per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

poll-total
The total number of consumer poll calls.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

process-rate
The average number of processed records per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

process-total
The total number of processed records.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

punctuate-rate
The average number of punctuate calls per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

punctuate-total
The total number of punctuate calls.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

task-created-rate
The average number of tasks created per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

task-created-total
The total number of tasks created.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

task-closed-rate
The average number of tasks closed per second.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

task-closed-total
The total number of tasks closed.
kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)

All of the following metrics have a recording level of debug, except for the dropped-records-* and
active-process-ratio metrics which have a recording level of info:

Metric/Attribute name
Description
Mbean name

process-latency-avg
The average execution time in ns, for processing.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

process-latency-max
The maximum execution time in ns, for processing.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

process-rate
The average number of processed records per second across all source processor nodes of this task.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

process-total
The total number of processed records across all source processor nodes of this task.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

commit-latency-avg
The average execution time in ns, for committing.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

commit-latency-max
The maximum execution time in ns, for committing.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

commit-rate
The average number of commit calls per second.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

commit-total
The total number of commit calls.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

record-lateness-avg
The average observed lateness of records (stream time – record timestamp).
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

record-lateness-max
The max observed lateness of records (stream time – record timestamp).
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

enforced-processing-rate
The average number of enforced processings per second.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

enforced-processing-total
The total number enforced processings.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

dropped-records-rate
The average number of records dropped within this task.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

dropped-records-total
The total number of records dropped within this task.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

active-process-ratio
The fraction of time the stream thread spent on processing this task among all assigned active tasks.
kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)

The following metrics are only available on certain types of nodes, i.e., the process-* metrics are only available for
source processor nodes, the suppression-emit-* metrics are only available for suppression operation nodes, and the
record-e2e-latency-* metrics are only available for source processor nodes and terminal nodes (nodes without successor
nodes).
All of the metrics have a recording level of debug, except for the record-e2e-latency-* metrics which have
a recording level of info:

Metric/Attribute name
Description
Mbean name

process-rate
The average number of records processed by a source processor node per second.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

process-total
The total number of records processed by a source processor node per second.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

suppression-emit-rate
The rate at which records that have been emitted downstream from suppression operation nodes.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

suppression-emit-total
The total number of records that have been emitted downstream from suppression operation nodes.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

record-e2e-latency-avg
The average end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

record-e2e-latency-max
The maximum end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

record-e2e-latency-min
The minimum end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)

All of the following metrics have a recording level of debug, except for the record-e2e-latency-* metrics which have a recording level trace>.
Note that the store-scope value is specified in StoreSupplier#metricsScope() for user’s customized state stores;
for built-in state stores, currently we have:

  • in-memory-state
  • in-memory-lru-state
  • in-memory-window-state
  • in-memory-suppression (for suppression buffers)
  • rocksdb-state (for RocksDB backed key-value store)
  • rocksdb-window-state (for RocksDB backed window store)
  • rocksdb-session-state (for RocksDB backed session store)

Metrics suppression-buffer-size-avg, suppression-buffer-size-max, suppression-buffer-count-avg, and suppression-buffer-count-max
are only available for suppression buffers. All other metrics are not available for suppression buffers.

Metric/Attribute name
Description
Mbean name

put-latency-avg
The average put execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-latency-max
The maximum put execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-if-absent-latency-avg
The average put-if-absent execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-if-absent-latency-max
The maximum put-if-absent execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

get-latency-avg
The average get execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

get-latency-max
The maximum get execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

delete-latency-avg
The average delete execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

delete-latency-max
The maximum delete execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-all-latency-avg
The average put-all execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-all-latency-max
The maximum put-all execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

all-latency-avg
The average all operation execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

all-latency-max
The maximum all operation execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

range-latency-avg
The average range execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

range-latency-max
The maximum range execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

flush-latency-avg
The average flush execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

flush-latency-max
The maximum flush execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

restore-latency-avg
The average restore execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

restore-latency-max
The maximum restore execution time in ns.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-rate
The average put rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-if-absent-rate
The average put-if-absent rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

get-rate
The average get rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

delete-rate
The average delete rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

put-all-rate
The average put-all rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

all-rate
The average all operation rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

range-rate
The average range rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

flush-rate
The average flush rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

restore-rate
The average restore rate for this store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

suppression-buffer-size-avg
The average total size, in bytes, of the buffered data over the sampling window.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)

suppression-buffer-size-max
The maximum total size, in bytes, of the buffered data over the sampling window.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)

suppression-buffer-count-avg
The average number of records buffered over the sampling window.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)

suppression-buffer-count-max
The maximum number of records buffered over the sampling window.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)

record-e2e-latency-avg
The average end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

record-e2e-latency-max
The maximum end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

record-e2e-latency-min
The minimum end-to-end latency of a record, measured by comparing the record timestamp with the system time when it has been fully processed by the node.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

RocksDB metrics are grouped into statistics-based metrics and properties-based metrics.
The former are recorded from statistics that a RocksDB state store collects whereas the latter are recorded from
properties that RocksDB exposes.
Statistics collected by RocksDB provide cumulative measurements over time, e.g. bytes written to the state store.
Properties exposed by RocksDB provide current measurements, e.g., the amount of memory currently used.
Note that the store-scope for built-in RocksDB state stores are currently the following:

  • rocksdb-state (for RocksDB backed key-value store)
  • rocksdb-window-state (for RocksDB backed window store)
  • rocksdb-session-state (for RocksDB backed session store)

RocksDB Statistics-based Metrics:
All of the following statistics-based metrics have a recording level of debug because collecting
statistics in

Metric/Attribute name
Description
Mbean name

bytes-written-rate
The average number of bytes written per second to the RocksDB state store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

bytes-written-total
The total number of bytes written to the RocksDB state store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

bytes-read-rate
The average number of bytes read per second from the RocksDB state store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

bytes-read-total
The total number of bytes read from the RocksDB state store.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

memtable-bytes-flushed-rate
The average number of bytes flushed per second from the memtable to disk.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

memtable-bytes-flushed-total
The total number of bytes flushed from the memtable to disk.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

memtable-hit-ratio
The ratio of memtable hits relative to all lookups to the memtable.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-data-hit-ratio
The ratio of block cache hits for data blocks relative to all lookups for data blocks to the block cache.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-index-hit-ratio
The ratio of block cache hits for index blocks relative to all lookups for index blocks to the block cache.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-filter-hit-ratio
The ratio of block cache hits for filter blocks relative to all lookups for filter blocks to the block cache.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

write-stall-duration-avg
The average duration of write stalls in ms.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

write-stall-duration-total
The total duration of write stalls in ms.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

bytes-read-compaction-rate
The average number of bytes read per second during compaction.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

bytes-written-compaction-rate
The average number of bytes written per second during compaction.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

number-open-files
The number of current open files.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

number-file-errors-total
The total number of file errors occurred.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

RocksDB Properties-based Metrics:
All of the following properties-based metrics have a recording level of info and are recorded when the
metrics are accessed.
If a state store consists of multiple RocksDB instances, as is the case for WindowStores and SessionStores,
each metric reports the sum over all the RocksDB instances of the state store, except for the block cache metrics
block-cache-*. The block cache metrics report the sum over all RocksDB instances if each instance uses its
own block cache, and they report the recorded value from only one instance if a single block cache is shared
among all instances.

Metric/Attribute name
Description
Mbean name

num-immutable-mem-table
The number of immutable memtables that have not yet been flushed.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

cur-size-active-mem-table
The approximate size of the active memtable in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

cur-size-all-mem-tables
The approximate size of active and unflushed immutable memtables in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

size-all-mem-tables
The approximate size of active, unflushed immutable, and pinned immutable memtables in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-entries-active-mem-table
The number of entries in the active memtable.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-entries-imm-mem-tables
The number of entries in the unflushed immutable memtables.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-deletes-active-mem-table
The number of delete entries in the active memtable.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-deletes-imm-mem-tables
The number of delete entries in the unflushed immutable memtables.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

mem-table-flush-pending
This metric reports 1 if a memtable flush is pending, otherwise it reports 0.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-running-flushes
The number of currently running flushes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

compaction-pending
This metric reports 1 if at least one compaction is pending, otherwise it reports 0.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-running-compactions
The number of currently running compactions.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

estimate-pending-compaction-bytes
The estimated total number of bytes a compaction needs to rewrite on disk to get all levels down to under
target size (only valid for level compaction).
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

total-sst-files-size
The total size in bytes of all SST files.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

live-sst-files-size
The total size in bytes of all SST files that belong to the latest LSM tree.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

num-live-versions
Number of live versions of the LSM tree.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-capacity
The capacity of the block cache in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-usage
The memory size of the entries residing in block cache in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

block-cache-pinned-usage
The memory size for the entries being pinned in the block cache in bytes.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

estimate-num-keys
The estimated number of keys in the active and unflushed immutable memtables and storage.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

estimate-table-readers-mem
The estimated memory in bytes used for reading SST tables, excluding memory used in block cache.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

background-errors
The total number of background errors.
kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)

All of the following metrics have a recording level of debug:

Metric/Attribute name
Description
Mbean name

hit-ratio-avg
The average cache hit ratio defined as the ratio of cache read hits over the total cache read requests.
kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)

hit-ratio-min
The mininum cache hit ratio.
kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)

hit-ratio-max
The maximum cache hit ratio.
kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)

We recommend monitoring GC time and other stats and various server stats such as CPU utilization, I/O service time, etc.

On the client side, we recommend monitoring the message/byte rate (global and per topic), request rate/size/time, and on the consumer side, max lag in messages among all partitions and min fetch request rate. For a consumer to keep up, max lag needs to be less than a threshold and min fetch rate needs to be larger than 0.

The current stable branch is 3.5. Kafka is regularly updated to include the latest release in the 3.5 series.

Operationally, we do the following for a healthy ZooKeeper installation:

  • Redundancy in the physical/hardware/network layout: try not to put them all in the same rack, decent (but don’t go nuts) hardware, try to keep redundant power and network paths, etc. A typical ZooKeeper ensemble has 5 or 7 servers, which tolerates 2 and 3 servers down, respectively. If you have a small deployment, then using 3 servers is acceptable, but keep in mind that you’ll only be able to tolerate 1 server down in this case.
  • I/O segregation: if you do a lot of write type traffic you’ll almost definitely want the transaction logs on a dedicated disk group. Writes to the transaction log are synchronous (but batched for performance), and consequently, concurrent writes can significantly affect performance. ZooKeeper snapshots can be one such a source of concurrent writes, and ideally should be written on a disk group separate from the transaction log. Snapshots are written to disk asynchronously, so it is typically ok to share with the operating system and message log files. You can configure a server to use a separate disk group with the dataLogDir parameter.
  • Application segregation: Unless you really understand the application patterns of other apps that you want to install on the same box, it can be a good idea to run ZooKeeper in isolation (though this can be a balancing act with the capabilities of the hardware).
  • Use care with virtualization: It can work, depending on your cluster layout and read/write patterns and SLAs, but the tiny overheads introduced by the virtualization layer can add up and throw off ZooKeeper, as it can be very time sensitive
  • ZooKeeper configuration: It’s java, make sure you give it ‘enough’ heap space (We usually run them with 3-5G, but that’s mostly due to the data set size we have here). Unfortunately we don’t have a good formula for it, but keep in mind that allowing for more ZooKeeper state means that snapshots can become large, and large snapshots affect recovery time. In fact, if the snapshot becomes too large (a few gigabytes), then you may need to increase the initLimit parameter to give enough time for servers to recover and join the ensemble.
  • Monitoring: Both JMX and the 4 letter words (4lw) commands are very useful, they do overlap in some cases (and in those cases we prefer the 4 letter commands, they seem more predictable, or at the very least, they work better with the LI monitoring infrastructure)
  • Don’t overbuild the cluster: large clusters, especially in a write heavy usage pattern, means a lot of intracluster communication (quorums on the writes and subsequent cluster member updates), but don’t underbuild it (and risk swamping the cluster). Having more servers adds to your read capacity.

Overall, we try to keep the ZooKeeper system as small as will handle the load (plus standard growth capacity planning) and as simple as possible. We try not to do anything fancy with the configuration or application layout as compared to the official release as well as keep it as self contained as possible. For these reasons, we tend to skip the OS packaged versions, since it has a tendency to try to put things in the OS standard hierarchy, which can be ‘messy’, for want of a better way to word it.

Use the following configuration option to specify which metrics you want collected:All of the following metrics have a recording level ofAll of the following metrics have a recording level ofAll of the following metrics have a recording level of, except for the dropped-records-* and active-process-ratio metrics which have a recording level ofThe following metrics are only available on certain types of nodes, i.e., the process-* metrics are only available for source processor nodes, the suppression-emit-* metrics are only available for suppression operation nodes, and the record-e2e-latency-* metrics are only available for source processor nodes and terminal nodes (nodes without successor nodes). All of the metrics have a recording level of, except for the record-e2e-latency-* metrics which have a recording level ofAll of the following metrics have a recording level of, except for the record-e2e-latency-* metrics which have a recording level. Note that thevalue is specified infor user’s customized state stores; for built-in state stores, currently we have:Metrics suppression-buffer-size-avg, suppression-buffer-size-max, suppression-buffer-count-avg, and suppression-buffer-count-max are only available for suppression buffers. All other metrics are not available for suppression buffers.RocksDB metrics are grouped into statistics-based metrics and properties-based metrics. The former are recorded from statistics that a RocksDB state store collects whereas the latter are recorded from properties that RocksDB exposes. Statistics collected by RocksDB provide cumulative measurements over time, e.g. bytes written to the state store. Properties exposed by RocksDB provide current measurements, e.g., the amount of memory currently used. Note that thefor built-in RocksDB state stores are currently the following:All of the following statistics-based metrics have a recording level ofbecause collecting statistics in RocksDB
may have an impact on performance
. Statistics-based metrics are collected every minute from the RocksDB state stores. If a state store consists of multiple RocksDB instances, as is the case for WindowStores and SessionStores, each metric reports an aggregation over the RocksDB instances of the state store.All of the following properties-based metrics have a recording level ofand are recorded when the metrics are accessed. If a state store consists of multiple RocksDB instances, as is the case for WindowStores and SessionStores, each metric reports the sum over all the RocksDB instances of the state store, except for the block cache metrics. The block cache metrics report the sum over all RocksDB instances if each instance uses its own block cache, and they report the recorded value from only one instance if a single block cache is shared among all instances.All of the following metrics have a recording level ofWe recommend monitoring GC time and other stats and various server stats such as CPU utilization, I/O service time, etc. On the client side, we recommend monitoring the message/byte rate (global and per topic), request rate/size/time, and on the consumer side, max lag in messages among all partitions and min fetch request rate. For a consumer to keep up, max lag needs to be less than a threshold and min fetch rate needs to be larger than 0.The current stable branch is 3.5. Kafka is regularly updated to include the latest release in the 3.5 series.Operationally, we do the following for a healthy ZooKeeper installation:Overall, we try to keep the ZooKeeper system as small as will handle the load (plus standard growth capacity planning) and as simple as possible. We try not to do anything fancy with the configuration or application layout as compared to the official release as well as keep it as self contained as possible. For these reasons, we tend to skip the OS packaged versions, since it has a tendency to try to put things in the OS standard hierarchy, which can be ‘messy’, for want of a better way to word it.

Kafka Streams is a client library for processing and analyzing data stored in Kafka. It builds upon important stream processing concepts such as properly distinguishing between event time and processing time, windowing support, exactly-once processing semantics and simple yet efficient management of application state.

Kafka Streams has a low barrier to entry: You can quickly write and run a small-scale proof-of-concept on a single machine; and you only need to run additional instances of your application on multiple machines to scale up to high-volume production workloads. Kafka Streams transparently handles the load balancing of multiple instances of the same application by leveraging Kafka’s parallelism model.

Learn More about Kafka Streams read this Section.

[Update] spaCy 101: Everything you need to know · spaCy Usage Documentation | persistence คือ – NATAVIGUIDES

spaCy 101: Everything you need to know

The most important concepts, explained in simple terms

Whether you’re new to spaCy, or just want to brush up on some NLP basics and
implementation details – this page should have you covered. Each section will
explain one of spaCy’s features in simple terms and with examples or
illustrations. Some sections will also reappear across the usage guides as a
quick introduction.

Help us improve the docs

Did you spot a mistake or come across explanations that are unclear? We always
appreciate improvement
suggestions or
pull requests. You can find a
“Suggest edits” link at the bottom of each page that points you to the source.

Take the free interactive course

Advanced NLP with spaCy

In this course you’ll learn how to use spaCy to build advanced natural language
understanding systems, using both rule-based and machine learning approaches. It
includes 55 exercises featuring interactive coding practice, multiple-choice
questions and slide decks.

Start the course

Features

In the documentation, you’ll come across mentions of spaCy’s features and
capabilities. Some of them refer to linguistic concepts, while others are
related to more general machine learning functionality.

NameDescriptionTokenizationSegmenting text into words, punctuations marks etc.Part-of-speech (POS) TaggingAssigning word types to tokens, like verb or noun.Dependency ParsingAssigning syntactic dependency labels, describing the relations between individual tokens, like subject or object.LemmatizationAssigning the base forms of words. For example, the lemma of “was” is “be”, and the lemma of “rats” is “rat”.Sentence Boundary Detection (SBD)Finding and segmenting individual sentences.Named Entity Recognition (NER)Labelling named “real-world” objects, like persons, companies or locations.Entity Linking (EL)Disambiguating textual entities to unique identifiers in a knowledge base.SimilarityComparing words, text spans and documents and how similar they are to each other.Text ClassificationAssigning categories or labels to a whole document, or parts of a document.Rule-based MatchingFinding sequences of tokens based on their texts and linguistic annotations, similar to regular expressions.TrainingUpdating and improving a statistical model’s predictions.SerializationSaving objects to files or byte strings.

Statistical models

While some of spaCy’s features work independently, others require
trained pipelines to be loaded, which enable spaCy to predict
linguistic annotations – for example, whether a word is a verb or a noun. A
trained pipeline can consist of multiple components that use a statistical model
trained on labeled data. spaCy currently offers trained pipelines for a variety
of languages, which can be installed as individual Python modules. Pipeline
packages can differ in size, speed, memory usage, accuracy and the data they
include. The package you choose always depends on your use case and the texts
you’re working with. For a general-purpose use case, the small, default packages
are always a good start. They typically include the following components:

  • Binary weights for the part-of-speech tagger, dependency parser and named
    entity recognizer to predict those annotations in context.
  • Lexical entries in the vocabulary, i.e. words and their
    context-independent attributes like the shape or spelling.
  • Data files like lemmatization rules and lookup tables.
  • Word vectors, i.e. multi-dimensional meaning representations of words that
    let you determine how similar they are to each other.
  • Configuration options, like the language and processing pipeline settings
    and model implementations to use, to put spaCy in the correct state when you
    load the pipeline.

Linguistic annotations

spaCy provides a variety of linguistic annotations to give you insights into a
text’s grammatical structure
. This includes the word types, like the parts of
speech, and how the words are related to each other. For example, if you’re
analyzing text, it makes a huge difference whether a noun is the subject of a
sentence, or the object – or whether “google” is used as a verb, or refers to
the website or company in a specific context.

Loading pipelines

python -m

spacy

download

en_core_web_sm



>>

>

import

spacy

>>

>

nlp

=

spacy.load

(

"en_core_web_sm"

)

Once you’ve downloaded and installed a trained pipeline, you
can load it via spacy.load. This will return a
Language object containing all components and data needed to process text. We
usually call it nlp. Calling the nlp object on a string of text will return
a processed Doc:

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"Apple is looking at buying U.K. startup for $1 billion"

)

for

token

in

doc

:

print

(

token

.

text

,

token

.

pos_

,

token

.

dep_

)

Even though a Doc is processed – e.g. split into individual words and
annotated – it still holds all information of the original text, like
whitespace characters. You can always get the offset of a token into the
original string, or reconstruct the original by joining the tokens and their
trailing whitespace. This way, you’ll never lose any information when processing
text with spaCy.

Tokenization

During processing, spaCy first tokenizes the text, i.e. segments it into
words, punctuation and so on. This is done by applying rules specific to each
language. For example, punctuation at the end of a sentence should be split off
– whereas “U.K.” should remain one token. Each Doc consists of individual
tokens, and we can iterate over them:

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"Apple is looking at buying U.K. startup for $1 billion"

)

for

token

in

doc

:

print

(

token

.

text

)

012345678910AppleislookingatbuyingU.K.startupfor$1billion

First, the raw text is split on whitespace characters, similar to
text.split(' '). Then, the tokenizer processes the text from left to right. On
each substring, it performs two checks:

  1. Does the substring match a tokenizer exception rule? For example, “don’t”
    does not contain whitespace, but should be split into two tokens, “do” and
    “n’t”, while “U.K.” should always remain one token.

  2. Can a prefix, suffix or infix be split off? For example punctuation like
    commas, periods, hyphens or quotes.

If there’s a match, the rule is applied and the tokenizer continues its loop,
starting with the newly split substrings. This way, spaCy can split complex,
nested tokens
like combinations of abbreviations and multiple punctuation
marks.

  • Tokenizer exception: Special-case rule to split a string into several
    tokens or prevent a token from being split when punctuation rules are
    applied.
  • Prefix: Character(s) at the beginning, e.g. $, (, , ¿.
  • Suffix: Character(s) at the end, e.g. km, ), , !.
  • Infix: Character(s) in between, e.g. -, --, /, .

While punctuation rules are usually pretty general, tokenizer exceptions
strongly depend on the specifics of the individual language. This is why each
available language has its own subclass, like
English or German, that loads in lists of hard-coded data and exception
rules.

📖

Tokenization rules

To learn more about how spaCy’s tokenization rules work in detail, how to
customize and replace the default tokenizer and how to add
language-specific data
, see the usage guides on
language data and
customizing the tokenizer.

Part-of-speech tags and dependencies

Needs model

After tokenization, spaCy can parse and tag a given Doc. This is where
the trained pipeline and its statistical models come in, which enable spaCy to
make predictions of which tag or label most likely applies in this context.
A trained component includes binary data that is produced by showing a system
enough examples for it to make predictions that generalize across the language –
for example, a word following “the” in English is most likely a noun.

Linguistic annotations are available as
Token attributes. Like many NLP libraries, spaCy
encodes all strings to hash values to reduce memory usage and improve
efficiency. So to get the readable string representation of an attribute, we
need to add an underscore _ to its name:

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"Apple is looking at buying U.K. startup for $1 billion"

)

for

token

in

doc

:

print

(

token

.

text

,

token

.

lemma_

,

token

.

pos_

,

token

.

tag_

,

token

.

dep_

,

token

.

shape_

,

token

.

is_alpha

,

token

.

is_stop

)

  • Text: The original word text.
  • Lemma: The base form of the word.
  • POS: The simple UPOS
    part-of-speech tag.
  • Tag: The detailed part-of-speech tag.
  • Dep: Syntactic dependency, i.e. the relation between tokens.
  • Shape: The word shape – capitalization, punctuation, digits.
  • is alpha: Is the token an alpha character?
  • is stop: Is the token part of a stop list, i.e. the most common words of
    the language?

TextLemmaPOSTagDepShapealphastopAppleapplePROPNNNPnsubjXxxxxTrueFalseisbeAUXVBZauxxxTrueTruelookinglookVERBVBGROOTxxxxTrueFalseatatADPINprepxxTrueTruebuyingbuyVERBVBGpcompxxxxTrueFalseU.K.u.k.PROPNNNPcompoundX.X.FalseFalsestartupstartupNOUNNNdobjxxxxTrueFalseforforADPINprepxxxTrueTrue$$SYM$quantmod$FalseFalse11NUMCDcompounddFalseFalsebillionbillionNUMCDpobjxxxxTrueFalse

Tip: Understanding tags and labels

Most of the tags and labels look pretty abstract, and they vary between
languages. spacy.explain will show you a short description – for example,
spacy.explain("VBZ") returns “verb, 3rd person singular present”.

Using spaCy’s built-in displaCy visualizer, here’s what
our example sentence and its dependencies look like:

📖

Part-of-speech tagging and morphology

To learn more about part-of-speech tagging and rule-based morphology, and
how to navigate and use the parse tree effectively, see the usage guides on
part-of-speech tagging and
using the dependency parse.

Named Entities

Needs model

A named entity is a “real-world object” that’s assigned a name – for example, a
person, a country, a product or a book title. spaCy can recognize various
types of named entities in a document, by asking the model for a
prediction
. Because models are statistical and strongly depend on the
examples they were trained on, this doesn’t always work perfectly and might
need some tuning later, depending on your use case.

Named entities are available as the ents property of a Doc:

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"Apple is looking at buying U.K. startup for $1 billion"

)

for

ent

in

doc

.

ents

:

print

(

ent

.

text

,

ent

.

start_char

,

ent

.

end_char

,

ent

.

label_

)

  • Text: The original entity text.
  • Start: Index of start of entity in the Doc.
  • End: Index of end of entity in the Doc.
  • Label: Entity label, i.e. type.

TextStartEndLabelDescriptionApple05ORGCompanies, agencies, institutions.U.K.2731GPEGeopolitical entity, i.e. countries, cities, states.$1 billion4454MONEYMonetary values, including unit.

Using spaCy’s built-in displaCy visualizer, here’s what
our example sentence and its named entities look like:

📖

Named Entity Recognition

To learn more about entity recognition in spaCy, how to add your own
entities
to a document and how to train and update the entity predictions
of a model, see the usage guides on
named entity recognition and
training pipelines.

Word vectors and similarity

Needs model

Similarity is determined by comparing word vectors or “word embeddings”,
multi-dimensional meaning representations of a word. Word vectors can be
generated using an algorithm like
word2vec and usually look like this:

banana.vector

array

(

[

2.02280000e-01

,

-

7.66180009e-02

,

3.70319992e-01

,

3.28450017e-02

,

-

4.19569999e-01

,

7.20689967e-02

,

-

3.74760002e-01

,

5.74599989e-02

,

-

1.24009997e-02

,

5.29489994e-01

,

-

5.23800015e-01

,

-

1.97710007e-01

,

-

3.41470003e-01

,

5.33169985e-01

,

-

2.53309999e-02

,

1.73800007e-01

,

1.67720005e-01

,

8.39839995e-01

,

5.51070012e-02

,

1.05470002e-01

,

3.78719985e-01

,

2.42750004e-01

,

1.47449998e-02

,

5.59509993e-01

,

1.25210002e-01

,

-

6.75960004e-01

,

3.58420014e-01

,

3.66849989e-01

,

2.52470002e-03

,

-

6.40089989e-01

,

-

2.97650009e-01

,

7.89430022e-01

,

3.31680000e-01

,

-

1.19659996e+00

,

-

4.71559986e-02

,

5.31750023e-01

]

,

dtype

=

float32

)

Important note

To make them compact and fast, spaCy’s small pipeline packages (all
packages that end in sm) don’t ship with word vectors, and only include
context-sensitive tensors. This means you can still use the similarity()
methods to compare documents, spans and tokens – but the result won’t be as
good, and individual tokens won’t have any vectors assigned. So in order to use
real word vectors, you need to download a larger pipeline package:

- python -m spacy download en_core_web_sm

+ python -m spacy download en_core_web_lg

Pipeline packages that come with built-in word vectors make them available as
the Token.vector attribute.
Doc.vector and Span.vector will
default to an average of their token vectors. You can also check if a token has
a vector assigned, and get the L2 norm, which can be used to normalize vectors.

import

spacy nlp

=

spacy

.

load

(

"en_core_web_md"

)

tokens

=

nlp

(

"dog cat banana afskfsd"

)

for

token

in

tokens

:

print

(

token

.

text

,

token

.

has_vector

,

token

.

vector_norm

,

token

.

is_oov

)

  • Text: The original token text.
  • has vector: Does the token have a vector representation?
  • Vector norm: The L2 norm of the token’s vector (the square root of the
    sum of the values squared)
  • OOV: Out-of-vocabulary

The words “dog”, “cat” and “banana” are all pretty common in English, so they’re
part of the pipeline’s vocabulary, and come with a vector. The word “afskfsd” on
the other hand is a lot less common and out-of-vocabulary – so its vector
representation consists of 300 dimensions of 0, which means it’s practically
nonexistent. If your application will benefit from a large vocabulary with
more vectors, you should consider using one of the larger pipeline packages or
loading in a full vector package, for example,
en_core_web_lg, which includes 685k unique
vectors
.

spaCy is able to compare two objects, and make a prediction of how similar
they are
. Predicting similarity is useful for building recommendation systems
or flagging duplicates. For example, you can suggest a user content that’s
similar to what they’re currently looking at, or label a support ticket as a
duplicate if it’s very similar to an already existing one.

Each Doc, Span, Token and
Lexeme comes with a .similarity
method that lets you compare it with another object, and determine the
similarity. Of course similarity is always subjective – whether two words, spans
or documents are similar really depends on how you’re looking at it. spaCy’s
similarity implementation usually assumes a pretty general-purpose definition of
similarity.

📝 Things to try

  1. Compare two different tokens and try to find the two most dissimilar
    tokens in the texts with the lowest similarity score (according to the
    vectors).
  2. Compare the similarity of two Lexeme objects, entries in
    the vocabulary. You can get a lexeme via the .lex attribute of a token.
    You should see that the similarity results are identical to the token
    similarity.

import

spacy nlp

=

spacy

.

load

(

"en_core_web_md"

)

doc1

=

nlp

(

"I like salty fries and hamburgers."

)

doc2

=

nlp

(

"Fast food tastes very good."

)

print

(

doc1

,

"<->"

,

doc2

,

doc1

.

similarity

(

doc2

)

)

french_fries

=

doc1

[

2

:

4

]

burgers

=

doc1

[

5

]

print

(

french_fries

,

"<->"

,

burgers

,

french_fries

.

similarity

(

burgers

)

)

What to expect from similarity results

Computing similarity scores can be helpful in many situations, but it’s also
important to maintain realistic expectations about what information it can
provide. Words can be related to each other in many ways, so a single
“similarity” score will always be a mix of different signals, and vectors
trained on different data can produce very different results that may not be
useful for your purpose. Here are some important considerations to keep in mind:

  • There’s no objective definition of similarity. Whether “I like burgers” and “I
    like pasta” is similar depends on your application. Both talk about food
    preferences, which makes them very similar – but if you’re analyzing mentions
    of food, those sentences are pretty dissimilar, because they talk about very
    different foods.
  • The similarity of Doc and Span objects defaults
    to the average of the token vectors. This means that the vector for “fast
    food” is the average of the vectors for “fast” and “food”, which isn’t
    necessarily representative of the phrase “fast food”.
  • Vector averaging means that the vector of multiple tokens is insensitive to
    the order
    of the words. Two documents expressing the same meaning with
    dissimilar wording will return a lower similarity score than two documents
    that happen to contain the same words while expressing different meanings.

💡

Tip: Check out sense2vec

sense2vec

sense2vec is a library developed by
us that builds on top of spaCy and lets you train and query more interesting and
detailed word vectors. It combines noun phrases like “fast food” or “fair game”
and includes the part-of-speech tags and entity labels. The library also
includes annotation recipes for our annotation tool Prodigy
that let you evaluate vectors and create terminology lists. For more details,
check out our blog post. To
explore the semantic similarities across all Reddit comments of 2015 and 2019,
see the interactive demo.

📖

Word vectors

To learn more about word vectors, how to customize them and how to load
your own vectors into spaCy, see the usage guide on
using word vectors and semantic similarities.

Pipelines

When you call nlp on a text, spaCy first tokenizes the text to produce a Doc
object. The Doc is then processed in several different steps – this is also
referred to as the processing pipeline. The pipeline used by the
trained pipelines typically include a tagger, a lemmatizer, a parser
and an entity recognizer. Each pipeline component returns the processed Doc,
which is then passed on to the next component.

  • Name: ID of the pipeline component.
  • Component: spaCy’s implementation of the component.
  • Creates: Objects, attributes and properties modified and set by the
    component.

NameComponentCreatesDescriptiontokenizerTokenizerDocSegment text into tokens.processing pipelinetaggerTaggerToken.tagAssign part-of-speech tags.parserDependencyParserToken.head, Token.dep, Doc.sents, Doc.noun_chunksAssign dependency labels.nerEntityRecognizerDoc.ents, Token.ent_iob, Token.ent_typeDetect and label named entities.lemmatizerLemmatizerToken.lemmaAssign base forms.textcatTextCategorizerDoc.catsAssign document labels.customcustom componentsDoc._.xxx, Token._.xxx, Span._.xxxAssign custom attributes, methods or properties.

The capabilities of a processing pipeline always depend on the components, their
models and how they were trained. For example, a pipeline for named entity
recognition needs to include a trained named entity recognizer component with a
statistical model and weights that enable it to make predictions of entity
labels. This is why each pipeline specifies its components and their settings in
the config:

[nlp]

pipeline

=

["tok2vec", "tagger", "parser", "ner"]

The statistical components like the tagger or parser are typically independent
and don’t share any data between each other. For example, the named entity
recognizer doesn’t use any features set by the tagger and parser, and so on.
This means that you can swap them, or remove single components from the pipeline
without affecting the others. However, components may share a “token-to-vector”
component like Tok2Vec or Transformer.
You can read more about this in the docs on
embedding layers.

Custom components may also depend on annotations set by other components. For
example, a custom lemmatizer may need the part-of-speech tags assigned, so it’ll
only work if it’s added after the tagger. The parser will respect pre-defined
sentence boundaries, so if a previous component in the pipeline sets them, its
dependency predictions may be different. Similarly, it matters if you add the
EntityRuler before or after the statistical entity
recognizer: if it’s added before, the entity recognizer will take the existing
entities into account when making predictions. The
EntityLinker, which resolves named entities to knowledge
base IDs, should be preceded by a pipeline component that recognizes entities
such as the EntityRecognizer.

The tokenizer is a “special” component and isn’t part of the regular pipeline.
It also doesn’t show up in nlp.pipe_names. The reason is that there can only
really be one tokenizer, and while all other pipeline components take a Doc
and return it, the tokenizer takes a string of text and turns it into a
Doc. You can still customize the tokenizer, though. nlp.tokenizer is
writable, so you can either create your own
Tokenizer class from scratch,
or even replace it with an
entirely custom function.

📖

Processing pipelines

To learn more about how processing pipelines work in detail, how to enable
and disable their components, and how to create your own, see the usage
guide on language processing pipelines.

Architecture

The central data structures in spaCy are the Language class,
the Vocab and the Doc object. The Language class
is used to process a text and turn it into a Doc object. It’s typically stored
as a variable called nlp. The Doc object owns the sequence of tokens and
all their annotations. By centralizing strings, word vectors and lexical
attributes in the Vocab, we avoid storing multiple copies of this data. This
saves memory, and ensures there’s a single source of truth.

Text annotations are also designed to allow a single source of truth: the Doc
object owns the data, and Span and Token are
views that point into it. The Doc object is constructed by the
Tokenizer, and then modified in place by the components
of the pipeline. The Language object coordinates these components. It takes
raw text and sends it through the pipeline, returning an annotated document.
It also orchestrates training and serialization.

Container objects

NameDescriptionDocA container for accessing linguistic annotations.DocBinA collection of Doc objects for efficient binary serialization. Also used for

training data

.ExampleA collection of training annotations, containing two Doc objects: the reference data and the predictions.LanguageProcessing class that turns text into Doc objects. Different languages implement their own subclasses of it. The variable is typically called nlp.LexemeAn entry in the vocabulary. It’s a word type with no context, as opposed to a word token. It therefore has no part-of-speech tag, dependency parse etc.SpanA slice from a Doc object.SpanGroupA named collection of spans belonging to a Doc.TokenAn individual token — i.e. a word, punctuation symbol, whitespace, etc.

Processing pipeline

The processing pipeline consists of one or more pipeline components that are
called on the Doc in order. The tokenizer runs before the components. Pipeline
components can be added using Language.add_pipe.
They can contain a statistical model and trained weights, or only make
rule-based modifications to the Doc. spaCy provides a range of built-in
components for different language processing tasks and also allows adding
custom components.

NameDescriptionAttributeRulerSet token attributes using matcher rules.DependencyParserPredict syntactic dependencies.EntityLinkerDisambiguate named entities to nodes in a knowledge base.EntityRecognizerPredict named entities, e.g. persons or products.EntityRulerAdd entity spans to the Doc using token-based rules or exact phrase matches.LemmatizerDetermine the base forms of words.MorphologizerPredict morphological features and coarse-grained part-of-speech tags.SentenceRecognizerPredict sentence boundaries.SentencizerImplement rule-based sentence boundary detection that doesn’t require the dependency parse.TaggerPredict part-of-speech tags.TextCategorizerPredict categories or labels over the whole document.Tok2VecApply a “token-to-vector” model and set its outputs.TokenizerSegment raw text and create Doc objects from the words.TrainablePipeClass that all trainable pipeline components inherit from.TransformerUse a transformer model and set its outputs.

Other functions

Automatically apply something to the Doc, e.g. to merge spans of tokens.

Matchers

Matchers help you find and extract information from Doc objects
based on match patterns describing the sequences you’re looking for. A matcher
operates on a Doc and gives you access to the matched tokens in context.

NameDescriptionDependencyMatcherMatch sequences of tokens based on dependency trees using Semgrex operators.MatcherMatch sequences of tokens, based on pattern rules, similar to regular expressions.PhraseMatcherMatch sequences of tokens based on phrases.

Other classes

NameDescriptionCorpusClass for managing annotated corpora for training and evaluation data.KnowledgeBaseStorage for entities and aliases of a knowledge base for entity linking.LookupsContainer for convenient access to large lookup tables and dictionaries.MorphAnalysisA morphological analysis.MorphologyStore morphological analyses and map them to and from hash values.ScorerCompute evaluation scores.StringStoreMap strings to and from hash values.VectorsContainer class for vector data keyed by string.VocabThe shared vocabulary that stores strings and gives you access to Lexeme objects.

Vocab, hashes and lexemes

Whenever possible, spaCy tries to store data in a vocabulary, the
Vocab, that will be shared by multiple documents. To save
memory, spaCy also encodes all strings to hash values – in this case for
example, “coffee” has the hash 3197928453018144401. Entity labels like “ORG”
and part-of-speech tags like “VERB” are also encoded. Internally, spaCy only
“speaks” in hash values.

  • Token: A word, punctuation mark etc. in context, including its
    attributes, tags and dependencies.
  • Lexeme: A “word type” with no context. Includes the word shape and
    flags, e.g. if it’s lowercase, a digit or punctuation.
  • Doc: A processed container of tokens in context.
  • Vocab: The collection of lexemes.
  • StringStore: The dictionary mapping hash values to strings, for example
    3197928453018144401 → “coffee”.

If you process lots of documents containing the word “coffee” in all kinds of
different contexts, storing the exact string “coffee” every time would take up
way too much space. So instead, spaCy hashes the string and stores it in the
StringStore. You can think of the StringStore as a
lookup table that works in both directions – you can look up a string to get
its hash, or a hash to get its string:

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"I love coffee"

)

print

(

doc

.

vocab

.

strings

[

"coffee"

]

)

print

(

doc

.

vocab

.

strings

[

3197928453018144401

]

)

Now that all strings are encoded, the entries in the vocabulary don’t need to
include the word text
themselves. Instead, they can look it up in the
StringStore via its hash value. Each entry in the vocabulary, also called
Lexeme, contains the context-independent information about
a word. For example, no matter if “love” is used as a verb or a noun in some
context, its spelling and whether it consists of alphabetic characters won’t
ever change. Its hash value will also always be the same.

import

spacy nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"I love coffee"

)

for

word

in

doc

:

lexeme

=

doc

.

vocab

[

word

.

text

]

print

(

lexeme

.

text

,

lexeme

.

orth

,

lexeme

.

shape_

,

lexeme

.

prefix_

,

lexeme

.

suffix_

,

lexeme

.

is_alpha

,

lexeme

.

is_digit

,

lexeme

.

is_title

,

lexeme

.

lang_

)

  • Text: The original text of the lexeme.
  • Orth: The hash value of the lexeme.
  • Shape: The abstract word shape of the lexeme.
  • Prefix: By default, the first letter of the word string.
  • Suffix: By default, the last three letters of the word string.
  • is alpha: Does the lexeme consist of alphabetic characters?
  • is digit: Does the lexeme consist of digits?

TextOrthShapePrefixSuffixis_alphais_digitI4690420944186131903XIITrueFalselove3702023516439754181xxxxloveTrueFalsecoffee3197928453018144401xxxxcfeeTrueFalse

The mapping of words to hashes doesn’t depend on any state. To make sure each
value is unique, spaCy uses a
hash function to calculate the
hash based on the word string. This also means that the hash for “coffee”
will always be the same, no matter which pipeline you’re using or how you’ve
configured spaCy.

However, hashes cannot be reversed and there’s no way to resolve
3197928453018144401 back to “coffee”. All spaCy can do is look it up in the
vocabulary. That’s why you always need to make sure all objects you create have
access to the same vocabulary. If they don’t, spaCy might not be able to find
the strings it needs.

import

spacy

from

spacy

.

tokens

import

Doc

from

spacy

.

vocab

import

Vocab nlp

=

spacy

.

load

(

"en_core_web_sm"

)

doc

=

nlp

(

"I love coffee"

)

print

(

doc

.

vocab

.

strings

[

"coffee"

]

)

print

(

doc

.

vocab

.

strings

[

3197928453018144401

]

)

empty_doc

=

Doc

(

Vocab

(

)

)

empty_doc

.

vocab

.

strings

.

add

(

"coffee"

)

print

(

empty_doc

.

vocab

.

strings

[

3197928453018144401

]

)

new_doc

=

Doc

(

doc

.

vocab

)

print

(

new_doc

.

vocab

.

strings

[

3197928453018144401

]

)

If the vocabulary doesn’t contain a string for 3197928453018144401, spaCy will
raise an error. You can re-add “coffee” manually, but this only works if you
actually know that the document contains that word. To prevent this problem,
spaCy will also export the Vocab when you save a Doc or nlp object. This
will give you the object and its encoded annotations, plus the “key” to decode
it.

Serialization

If you’ve been modifying the pipeline, vocabulary, vectors and entities, or made
updates to the component models, you’ll eventually want to save your
progress
– for example, everything that’s in your nlp object. This means
you’ll have to translate its contents and structure into a format that can be
saved, like a file or a byte string. This process is called serialization. spaCy
comes with built-in serialization methods and supports the
Pickle protocol.

What’s pickle?

Pickle is Python’s built-in object persistence system. It lets you transfer
arbitrary Python objects between processes. This is usually used to load an
object to and from disk, but it’s also used for distributed computing, e.g.
with
PySpark
or Dask. When you unpickle an object, you’re agreeing to
execute whatever code it contains. It’s like calling eval() on a string – so
don’t unpickle objects from untrusted sources.

All container classes, i.e. Language (nlp),
Doc, Vocab and StringStore
have the following methods available:

MethodReturnsExampleto_bytesbytesdata = nlp.to_bytes()from_bytesobjectnlp.from_bytes(data)to_disknlp.to_disk("/path")from_diskobjectnlp.from_disk("/path")

📖

Saving and loading

To learn more about how to save and load your own pipelines, see the usage
guide on saving and loading.

Training

spaCy’s tagger, parser, text categorizer and many other components are powered
by statistical models. Every “decision” these components make – for example,
which part-of-speech tag to assign, or whether a word is a named entity – is a
prediction based on the model’s current weight values. The weight values
are estimated based on examples the model has seen during training. To train
a model, you first need training data – examples of text, and the labels you
want the model to predict. This could be a part-of-speech tag, a named entity or
any other information.

Training is an iterative process in which the model’s predictions are compared
against the reference annotations in order to estimate the gradient of the
loss
. The gradient of the loss is then used to calculate the gradient of the
weights through backpropagation. The gradients
indicate how the weight values should be changed so that the model’s predictions
become more similar to the reference labels over time.

  • Training data: Examples and their annotations.
  • Text: The input text the model should predict a label for.
  • Label: The label the model should predict.
  • Gradient: The direction and rate of change for a numeric value.
    Minimising the gradient of the weights should result in predictions that are
    closer to the reference labels on the training data.

When training a model, we don’t just want it to memorize our examples – we want
it to come up with a theory that can be generalized across unseen data.
After all, we don’t just want the model to learn that this one instance of
“Amazon” right here is a company – we want it to learn that “Amazon”, in
contexts like this, is most likely a company. That’s why the training data
should always be representative of the data we want to process. A model trained
on Wikipedia, where sentences in the first person are extremely rare, will
likely perform badly on Twitter. Similarly, a model trained on romantic novels
will likely perform badly on legal text.

This also means that in order to know how the model is performing, and whether
it’s learning the right things, you don’t only need training data – you’ll
also need evaluation data. If you only test the model with the data it was
trained on, you’ll have no idea how well it’s generalizing. If you want to train
a model from scratch, you usually need at least a few hundred examples for both
training and evaluation.

📖

Training pipelines and models

To learn more about training and updating pipelines, how to create training
data and how to improve spaCy’s named models, see the usage guides on
training.

Training config and lifecycle

Training config files include all settings and hyperparameters for training
your pipeline. Instead of providing lots of arguments on the command line, you
only need to pass your config.cfg file to spacy train.
This also makes it easy to integrate custom models and architectures, written in
your framework of choice. A pipeline’s config.cfg is considered the “single
source of truth”, both at training and runtime.

config.cfg (excerpt)

[training]

accumulate_gradient

=

3

[training.optimizer]

@optimizers

=

"Adam.v1"

[training.optimizer.learn_rate]

@schedules

=

"warmup_linear.v1"

warmup_steps

=

250

total_steps

=

20000

initial_rate

=

0.01

📖

Training configuration system

For more details on spaCy’s configuration system and how to use it to
customize your pipeline components, component models, training settings and
hyperparameters, see the training config usage guide.

Trainable components

spaCy’s Pipe class helps you implement your own trainable
components that have their own model instance, make predictions over Doc
objects and can be updated using spacy train. This lets you
plug fully custom machine learning components into your pipeline that can be
configured via a single training config.

config.cfg (excerpt)

[components.my_component]

factory

=

"my_component"

[components.my_component.model]

@architectures

=

"my_model.v1"

width

=

128

📖

Custom trainable components

To learn more about how to implement your own model architectures and use
them to power custom trainable components, see the usage guides on the
trainable component API and
implementing layers and architectures
for trainable components.

Language data

Every language is different – and usually full of exceptions and special
cases
, especially amongst the most common words. Some of these exceptions are
shared across languages, while others are entirely specific – usually so
specific that they need to be hard-coded. The
lang module contains all language-specific data,
organized in simple Python files. This makes the data easy to update and extend.

The shared language data in the directory root includes rules that can be
generalized across languages – for example, rules for basic punctuation, emoji,
emoticons and single-letter abbreviations. The individual language data in a
submodule contains rules that are only relevant to a particular language. It
also takes care of putting together all components and creating the
Language subclass – for example, English or German. The
values are defined in the Language.Defaults.

from

spacy

.

lang

.

en

import

English

from

spacy

.

lang

.

de

import

German nlp_en

=

English

(

)

nlp_de

=

German

(

)

NameDescriptionStop words
stop_words.pyList of most common words of a language that are often useful to filter out, for example “and” or “I”. Matching tokens will return True for is_stop.Tokenizer exceptions
tokenizer_exceptions.pySpecial-case rules for the tokenizer, for example, contractions like “can’t” and abbreviations with punctuation, like “U.K.”.Punctuation rules
punctuation.pyRegular expressions for splitting tokens, e.g. on punctuation or special characters like emoji. Includes rules for prefixes, suffixes and infixes.Character classes
char_classes.pyCharacter classes to be used in regular expressions, for example, Latin characters, quotes, hyphens or icons.Lexical attributes
lex_attrs.pyCustom functions for setting lexical attributes on tokens, e.g. like_num, which includes language-specific words like “ten” or “hundred”.Syntax iterators
syntax_iterators.pyFunctions that compute views of a Doc object based on its syntax. At the moment, only used for noun chunks.Lemmatizer
lemmatizer.py spacy-lookups-dataCustom lemmatizer implementation and lemmatization tables.

Community & FAQ

We’re very happy to see the spaCy community grow and include a mix of people
from all kinds of different backgrounds – computational linguistics, data
science, deep learning, research and more. If you’d like to get involved, below
are some answers to the most important questions and resources for further
reading.

Help, my code isn’t working!

Bugs suck, and we’re doing our best to continuously improve the tests and fix
bugs as soon as possible. Before you submit an issue, do a quick search and
check if the problem has already been reported. If you’re having installation or
loading problems, make sure to also check out the
troubleshooting guide. Help with spaCy is available
via the following platforms:

How do I know if something is a bug?

Of course, it’s always hard to know for sure, so don’t worry – we’re not going
to be mad if a bug report turns out to be a typo in your code. As a simple
rule, any C-level error without a Python traceback, like a segmentation
fault
or memory error, is always a spaCy bug.

Because models are statistical, their performance will never be perfect.
However, if you come across patterns that might indicate an underlying
issue
, please do file a report. Similarly, we also care about behaviors that
contradict our docs.

  • Stack Overflow: Usage
    questions
    and everything related to problems with your specific code. The
    Stack Overflow community is much larger than ours, so if your problem can be
    solved by others, you’ll receive help much quicker.
  • GitHub discussions

    : General
    discussion
    , project ideas and usage questions. Meet other community
    members to get help with a specific code implementation, discuss ideas for new
    projects/plugins, support more languages, and share best practices.

  • GitHub issue tracker

    : Bug
    reports
    and improvement suggestions, i.e. everything that’s likely
    spaCy’s fault. This also includes problems with the trained pipelines beyond
    statistical imprecisions, like patterns that point to a bug.

Important note

Please understand that we won’t be able to provide individual support via email.
We also believe that help is much more valuable if it’s shared publicly, so that
more people can benefit from it. If you come across an issue and you think
you might be able to help, consider posting a quick update with your solution.
No matter how simple, it can easily save someone a lot of time and headache –
and the next time you need help, they might repay the favor.

How can I contribute to spaCy?

You don’t have to be an NLP expert or Python pro to contribute, and we’re happy
to help you get started. If you’re new to spaCy, a good place to start is the
help wanted (easy) label
on GitHub, which we use to tag bugs and feature requests that are easy and
self-contained. We also appreciate contributions to the docs – whether it’s
fixing a typo, improving an example or adding additional explanations. You’ll
find a “Suggest edits” link at the bottom of each page that points you to the
source.

Another way of getting involved is to help us improve the
language data – especially if you
happen to speak one of the languages currently in
alpha support. Even adding simple tokenizer
exceptions, stop words or lemmatizer data can make a big difference. It will
also make it easier for us to provide a trained pipeline for the language in the
future. Submitting a test that documents a bug or performance issue, or covers
functionality that’s especially important for your application is also very
helpful. This way, you’ll also make sure we never accidentally introduce
regressions to the parts of the library that you care about the most.

For more details on the types of contributions we’re looking for, the code
conventions and other useful tips, make sure to check out the
contributing guidelines.

Code of Conduct

spaCy adheres to the
Contributor Covenant Code of Conduct.
By participating, you are expected to uphold this code.

I’ve built something cool with spaCy – how can I get the word out?

First, congrats – we’d love to check it out! When you share your project on
Twitter, don’t forget to tag @spacy_io so we
don’t miss it. If you think your project would be a good fit for the
spaCy Universe, feel free to submit it! Tutorials are also
incredibly valuable to other users and a great way to get exposure. So we
strongly encourage writing up your experiences, or sharing your code and
some tips and tricks on your blog. Since our website is open-source, you can add
your project or tutorial by making a pull request on GitHub.

If you would like to use the spaCy logo on your site, please get in touch and
ask us first. However, if you want to show support and tell others that your
project is using spaCy, you can grab one of our spaCy badges here:

[![Built with spaCy](https://img.shields.io/badge/built%20with-spaCy-09a3d5.svg)

](https://spacy.io)

[![Built with spaCy](https://img.shields.io/badge/made%20with%20❤%20and-spaCy-09a3d5.svg)

](https://spacy.io)


อยากรวย ต้องอ่าน THINK AND GROW RICH คิดแล้วรวย EP8 การยืนหยัด Persistence


🔥แจกหนังสือฟรี🔥\” เงิน มา ง่าย ๆ\” เขียนโดย อ.วรัทภพ รชตนามวงษ์ มีเนื้อหามากถึง 357 หน้า รับหนังสือฟรี! กดลิงก์นี้ด่วน ของมีจำนวนจำกัด 👉 https://get.moneyeasybook.com/?ref=YTA20190831
วันนี้ผมจะมา รีวิว แนะนำหนังสือ ขายดีระดับโลกที่ชื่อว่า
THINK AND GROW RICH หรือชื่อภาษาไทย คือ \” คิดแล้วรวย\”
ซึ่งใจความสำคัญของหนังสือเล่มนี้มีอยู่ 13 หัวข้อ
คลิปนี้ ผมจะมาสรุปให้เข้าใจหัวข้อที่ 8 ซึ่งก็คือ
การยืนหยัด Persistence
ลองชมดูครับ
🔴 พบกับวิดีโอใหม่ทุกวัน 🔴 ถ้าคุณอยากประสบความสำเร็จและรวย \”เร็วขึ้น\”
จากประสบการณ์การทำธุรกิจไทยจีน มาแล้ว 14 ธุรกิจของผม
👇 คลิกลิงก์แล้วกด “SUBSCRIBE ติดตาม และกดกระดิ่งแจ้งเตือน ตอนนี้เลย!! 👇
https://www.youtube.com/channel/UC6GkGouzOitA6vUzOEBEqwA?sub_confirmation=1

// ดูวิดีโอของ \”วรัทภพ\” ตามเพลย์ลิสต์
วิธีขายของ LAZADA
https://bit.ly/2TUxuRn
วิธีสั่งสินค้าจากจีน
https://bit.ly/2IERdmE
การทำตลาดจีน และส่งออกจีน สำหรับสินค้าไทย
https://bit.ly/2GWdITq
วิธีขายสินค้าแบบ ดรอปชิป (Dropship)
http://bit.ly/2x2sOPf
วิธีเริ่มต้นธุรกิจ ในปัจจุบัน
https://bit.ly/2ChCNT7
ความรู้ หาเงิน เพิ่มรายได้ ที่จะทำให้คุณรวยเร็วขึ้น
https://bit.ly/2CR2Jqc
เคล็ดลับ การตลาดและการขาย
https://bit.ly/2M8P7cV
ไอเดียธุรกิจเงินล้าน
https://bit.ly/2TrY2IT
พัฒนาตัวเอง เพื่อความสำเร็จในด้านที่ต้องการ
https://bit.ly/2LTPms2
แรงบันดาลใจและกำลังใจ ในการใช้ชีวิต
https://bit.ly/2TKQAbW
แกะคำคม ข้อคิด นักปราชญ์ และนักธุรกิจ
https://bit.ly/2SDzHjh
WARATTAPOB PODCAST (เสียงจาก วรัทภพ)
https://bit.ly/2SBlrHR
VLOG IN CHINA ชีวิตในจีน กินเที่ยว
https://bit.ly/2AqaFNB
รีวิว ธุรกิจจีนและเศรษฐกิจจีน
https://bit.ly/2M8Phkx
VLOG IN THAILAND ชีวิตในไทย
https://bit.ly/2AUvnWf

// วรัทภพ รชตนามวงษ์ คือ ใคร?
ผม \”วรัทภพ รชตนามวงษ์\” เป็นคนไทย เกิดที่จังหวัดเชียงใหม่
เป็นผู้ประกอบการที่ทำธุรกิจมาแล้ว 14 ธุรกิจ
ทั้งในประเทศไทย และ จีน ตั้งแต่ปี พ.ศ.2545 จนถึงปัจจุบัน
ผมตั้งใจทำสื่อเพื่อแบ่งปันความรู้และประสบการณ์
ให้คนรุ่นใหม่ที่อยากประสบความสำเร็จในชีวิตและรวย “เร็วขึ้น”

// ติดตาม วรัทภพ รชตนามวงษ์ เพิ่มเติมได้ที่
Website : https://www.warattapob.com
SOCIAL
Instagram : https://www.instagram.com/warattapob_rachatanamwong
Facebook : https://fb.me/WarattapobRachatanamwong
YouTube: https://www.youtube.com/c/WarattapobRachatanamwong
Line official : http://line.me/ti/p/~@warattapob
Twitter : https://twitter.com/warattapob
PODCAST
สำหรับ Android
Soundcloud : https://bit.ly/2QjfVYm
Spotify : https://spoti.fi/2Jcwh6Y
สำหรับ iOS
Apple Podcast : https://apple.co/2QjW5fM

WARATTAPOB คิดแล้วรวย อยากรวย
วิดีโอนี้เกี่ยวกับ อยากรวย ต้องอ่าน THINK AND GROW RICH คิดแล้วรวย EP8 การยืนหยัด Persistence
LINK https://youtu.be/IE3o3LZSPJI
LINK https://youtu.be/IE3o3LZSPJI

นอกจากการดูบทความนี้แล้ว คุณยังสามารถดูข้อมูลที่เป็นประโยชน์อื่นๆ อีกมากมายที่เราให้ไว้ที่นี่: ดูความรู้เพิ่มเติมที่นี่

อยากรวย ต้องอ่าน THINK AND GROW RICH คิดแล้วรวย EP8 การยืนหยัด Persistence

การ run MySQL ใน 5 นาที ด้วย docker พร้อมการ persist data ด้วย docker volume


👁 เทคนิคต่าง ๆ ที่ใช้ในคลิป
1. การ pull image จาก docker
2. การแสดง images ที่มีในเครื่อง
3. การ run mysql container
4. การทำ data persistence ด้วย volume เพื่อเก็บข้อมูลของฐานข้อมูลไว้
script สำคัญที่ใช้ในคลิปนี้
docker version
 pull docker image
docker pull mysql
 list images
docker images
 run mysql on docker
docker run name dolphin rm p 3306:3306 e MYSQL_ROOT_PASSWORD=banana d mysql
 list processes
docker ps a
 exec command in container
docker exec it dolphin mysql u root p
 connect to mysql from terminal
mysql u root p h localhost P 3306 protocol=tcp
mysql u root p P 3306 protocol=tcp
mysqlsh [email protected]:3306 sql
 stop process
docker stop dolphin
 persist data (using volume)
docker run name dolphin rm p 3306:3306 d e MYSQL_ROOT_PASSWORD=banana v mysqlvolume:/var/lib/mysql mysql
เชิญสมัครเป็นสมาชิกของช่องนี้ได้ที่ ► https://www.youtube.com/subscription_center?add_user=prasertcbs
สอน docker ► https://www.youtube.com/watch?v=CFIwQvBY_MM\u0026list=PLoTScYm9O0GGJV7UpJs6NVvsf6qaKja9_
สอน MySQL ► https://www.youtube.com/playlist?list=PLoTScYm9O0GFmJDsZipFCrY6L0RrBYLT
สอน PostgreSQL ► https://www.youtube.com/playlist?list=PLoTScYm9O0GGi_NqmIu43BPsxA0wtnyH
สอน Microsoft SQL Server 2012, 2014, 2016, 2017 ► https://www.youtube.com/playlist?list=PLoTScYm9O0GH8gYuxppjqu5Blc7KbQVn
สอน SQLite ► https://www.youtube.com/playlist?list=PLoTScYm9O0GHjYJA4pfG38M5BcrWKf5s2
สอน SQL สำหรับ Data Science ► https://www.youtube.com/playlist?list=PLoTScYm9O0GGq8M6HO8xrpkaRhvEBsQhw
การเชื่อมต่อกับฐานข้อมูล (SQL Server, MySQL, SQLite) ด้วย Python ► https://www.youtube.com/playlist?list=PLoTScYm9O0GEdZtHwU3t9k3dBAlxYoq59
การใช้ Excel ในการทำงานร่วมกับกับฐานข้อมูล (SQL Server, MySQL, Access) ► https://www.youtube.com/playlist?list=PLoTScYm9O0GGA2sSqNRSXlw0OYuCfDwYk
prasertcbs_SQL prasertcbs prasertcbs_MySQL docker

การ run MySQL ใน 5 นาที ด้วย docker พร้อมการ persist data ด้วย docker volume

Docker Tutorial for Beginners [FULL COURSE in 3 Hours]


Full Docker Tutorial | Complete Docker Course | Handson course with a lot of demos and explaining the concepts behind, so that you really understand it.
💙 Become a Kubernetes Administrator CKA: https://bit.ly/3lUeDES
💚 Become a DevOps Engineer full educational program: https://bit.ly/3gEwf4V
🧡 Udemy courses: http://bit.ly/2OgvzIO
► Follow me on IG for behind the scenes content: 👉🏼 https://bit.ly/2F3LXYJ
docker dockertutorial techworldwithnana
By the end, you will have a deep understanding of the concepts and a great overall big picture of how Docker is used in the whole software development process.
The course is a mix of animated theoretic explanation and handson demo’s to follow along, so you get your first handson experience with Docker and feel more confident using it in your project.
▬▬▬▬▬▬ T I M E S T A M P S ⏰ ▬▬▬▬▬▬
0:00 Intro and Course Overview
01:58 What is Docker?
10:56 What is a Container?
19:40 Docker vs Virtual Machine
23:53 Docker Installation
42:02 Main Docker Commands
57:15 Debugging a Container
1:06:39 Demo Project Overview Docker in Practice
1:10:08 Developing with Containers
1:29:49 Docker Compose Running multiple services
1:42:02 Dockerfile Building our own Docker Image
2:04:36 Private Docker Repository Pushing our built Docker Image into a private Registry on AWS
2:19:06 Deploy our containerized app
2:27:26 Docker Volumes Persist data in Docker
2:33:03 Volumes Demo Configure persistence for our demo project
2:45:13 Wrap Up
🔗 Links
► Developing with Containers Demo project: https://gitlab.com/nanuchi/techworldjsdockerdemoapp
🚀 1. What is Docker?
► What is a container and what problems does it solve?
► Container repository where do containers live?
🚀 2. What is a Container technically
► What is a container technically? (layers of images)
► Demo part (docker hub and run a docker container locally)
🚀 3. Docker vs Virtual Machine
🚀 4. Docker Installation
► Before Installing Docker prerequisites
► Install docker on Mac, Windows, Linux
❗️ Note: Docker Toolbox has been deprecated. Please use Docker Desktop instead. See for Mac (https://docs.docker.com/dockerformac/) and for Windows (https://docs.docker.com/dockerforwindows/).
🚀 5. Main Docker Commands
► docker pull, docker run, docker ps, docker stop, docker start, port mapping
🚀 6. Debugging a Container
► docker logs, docker exec it
🚀 7. Demo Project Overview Docker in Practice (Nodejs App with MongoDB and MongoExpress UI)
🚀 8. Developing with Containers
► JavaScript App (HTML, JavaScript Frontend, Node.js Backend)
► MongoDB and Mongo Express SetUp with Docker
► Docker Network concept and demo
🚀 9. Docker Compose Running multiple services
► What is Docker Compose?
► How to use it Create the Docker Compose File
► Docker Networking in Docker Compose
🚀 10. Dockerfile Building our own Docker Image
► What is a Dockerfile?
► Create the Dockerfile
► Build an image with Dockerfile
🚀 11. Private Docker Repository Pushing our built Docker Image into a private Registry on AWS
► Private Repository on AWS ECR
► docker login
► docker tag
► Push Docker Image to the Private Repo
🚀 12. Deploy our containerized application
🚀 13. Docker Volumes Persist data in Docker
► When do we need Docker Volumes?
► What is Docker Volumes?
► Docker Volumes Types
🚀 14. Volumes Demo Configure persistence for our demo project
▬▬▬▬▬▬ Want to learn more? 🚀 ▬▬▬▬▬▬
DevOps Tools, like GitHub Actions, Terraform ► https://bit.ly/2W9UEq6
Jenkins Pipeline Tutorials ► https://bit.ly/2Wunx08
Full Kubernetes tutorial ► https://www.youtube.com/playlist?list=PLy7NrYWoggjziYQIDorlXjTvvwweTYoNC
▬▬▬▬▬▬ Connect with me 👋 ▬▬▬▬▬▬
Join private FB group ► https://bit.ly/32UVSZP
INSTAGRAM ► https://bit.ly/2F3LXYJ
TWITTER ► https://bit.ly/3i54PUB
LINKEDIN ► https://bit.ly/3hWOLVT
▬▬▬▬▬▬ Courses \u0026 Ebooks \u0026 Bootcamp 🚀 ▬▬▬▬▬▬
► Become a DevOps Engineer full educational program 👉🏼 https://bit.ly/3gEwf4V
► Udemy courses get biggest discounts here 👉🏼 http://bit.ly/2OgvzIO
► Kubernetes 101 compact and easytoread ebook bundle 👉🏼 https://bit.ly/3mPIaiU

Docker Tutorial for Beginners [FULL COURSE in 3 Hours]

Personal Development | Powerful Jim Rohn Motivational Compilation


You can have more, because you can become more Jim Rohn
In this motivational speech compilation Jim Rohn talks about Personal Development. The only way to have more in life is to become more. If you will change, everything will change for you. You don’t have to change what’s outside, rather, you have to change what’s inside you. Become a person of value. Do something different the next 90 days, than the last 90 days, and you will have different results.
Subscribe to our channel using this link for a constant flow of instructional and motivational videos from great speakers like Jim Rohn : https://www.youtube.com/c/MotivationalStories2020?sub_confirmation=1
MotivationalStories JimRohn
FAIRUSE COPYRIGHT DISCLAIMER
Copyright Disclaimer Under Section 107 of the Copyright Act 1976, allowance is made for \”fair use\” for purposes such as criticism, commenting, news reporting, teaching, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Nonprofit, educational or personal use tips the balance in favor of fair use.
1) This video has no negative impact on the original works
2) This video is also for teaching purposes.
3) It is transformative in nature.

Personal Development | Powerful Jim Rohn Motivational Compilation

Ocean Protocol เหรียญ OCEAN คืออะไร


สมัครฟรี กระเป๋าเงินดิจิทัล รับ จ่าย สินทรัพย์ดิจิทัล สามารถเทรดได้24ชม.เปิด7วันไม่มีวันหยุด เปิดบัญชีเทรดสินทรัพย์ดิจิทัล คริบโตกับบิทคับ
คลิก! สมัครฟรี https://www.bitkub.com/signup?ref=20288
วิธีการยืนยันตัวตนฺบิทคับBitkubสำหรับบุคคลสัญชาติไทย (KYC Level 1)
https://bit.ly/2SS1669

ข่าวสารคริปโท
Ocean Protocol เหรียญ OCEAN คือ ออะไร
กระดานBitkub
ข่าวสารคริปโท OCEAN OceanProtocol สมัครbitkub
bitkub สินทรัพย์ดิจิทัล เหรียญ คอลย์
การลงทุนในสินทรัพย์ดิจิทัลมีความเสี่ยงสูง ควรศึกษาและทำความเข้าใจก่อนลงทุน
ขอบคุณ เครดิต ที่มา
https://www.bitkub.com/signup?ref=20288
https://oceanprotocol.com/
https://coinmarketcap.com/
https://medium.com/bitkub/whatisocean204b4b2414e3

Ocean Protocol   เหรียญ OCEAN   คืออะไร

นอกจากการดูบทความนี้แล้ว คุณยังสามารถดูข้อมูลที่เป็นประโยชน์อื่นๆ อีกมากมายที่เราให้ไว้ที่นี่: ดูวิธีอื่นๆLEARN FOREIGN LANGUAGE

ขอบคุณมากสำหรับการดูหัวข้อโพสต์ persistence คือ

Leave a Reply

Your email address will not be published. Required fields are marked *