Kafka 0.10.0 Documentation

以前のリリース: 0.7.x, 0.8.0, 0.8.1.X, 0.8.2.X, 0.9.0.X.

1. 開始

1.1はじめに

Kafkaは分散、パーティション、リプリケートされたコミットログのサービスです。ユニークな設計のメッセージシステムの機能を提供します。

どういうことか?

まず、いくつかの基本的なメッセージ技術用語を復習してみましょう:

つまり、高レベルにおいて、以下のようにプロデューサはネットワークを通じてメッセージをコンシューマに順番に提供するKafkaクラスタにメッセージを送信します:
クライアントとサーバの間の通信は、単純、高パフォーマンス、言語に寛容な TCP プロトコルを使って行われます。KafkaについてはJavaクライアントを提供しますが、クライアントは多くの言語で利用可能です。

トピックスとログ

Kafkaが提供する高レベル作用に初めて飛び込んでみましょう - トピック

トピックはメッセージが発行されるカテゴリあるいはフィード名です。各トピックについては、Kafkaクラスタが以下のように見えるパーティション化されたログを維持します:

各パーティションは、コミットログに絶え間なく追加される順番のある、不変のメッセージの順列です。パーティション内のメッセージはオフセット と呼ばれるパーティション内で各メッセージを一意に識別する連続するid番号が割り当てられます。

Kafka クラスタは設定可能な期間の間、それらが消費されたかどうかに関係なく、全ての発行されたメッセージを保持します例えばログの保存が2日に設定された場合、メッセージが発行されてから2日間は消費可能です。その後、スペースを解放するために削除されるでしょう。Kafkaのパフォーマンスはデータのサイズに対して事実上一定です。つまり多くのデータを保持する事は問題になりません。

In fact the only metadata retained on a per-consumer basis is the position of the consumer in the log, called the "offset". This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads messages, but in fact the position is controlled by the consumer and it can consume messages in any order it likes. たとえば、コンシューマは再処理のために古いオフセットへ再設定することができます。

この機能の組み合わせは、Kafkaのコンシューマがとても手軽であることを意味します。それらはクラスタあるいは他のコンシューマに大きな影響無しに行き来することができます。例えば、既存のコンシューマによって消費されるものを変更せずに、任意のトピックの内容を"tail"するためにコマンドラインツールを使うことができます。

ログ内のパーティションはいくつかの目的のために提供されます。まず、それらは一つのサーバに収まるサイズを超えてログをスケールすることができます。個々のパーティションはそれをホストするサーバに収まらなければなりませんが、トピックは多くのパーティションを持つことができるので、任意の量のデータを処理することができます。Second they act as the unit of parallelism—more on that in a bit.

分散

ログのパーティションはKafkaクラスタのサーバ上で各サーバのデータ処理とパーティションの共有のリクエストを使って分散されます。各パーティションは耐障害性のための設定可能なサーバ数までリプリケートされます。

各パーティションは"leader"として振る舞う1つのサーバと"followers"と振る舞う0個以上のサーバを持ちます。leaderはパーティションの全てのreadとwriteを処理し、followerは受動的にleaderをリプリケートします。leaderが故障すると、followerの一つが自動的に新しいleaderになるでしょう。各サーバは幾つかのパーティションに対してleaderとして振る舞い、followerは他のパーティションに対してそう振る舞います。つまり負荷はクラスタ内でよくバランスされています。

プロデューサ

プロデューサはそれらが選択したトピックへデータを発行します。プロデューサはトピック内でどのメッセージがどのパーティションへ割り当てられるかに責任があります。これは負荷をバランスするために単純にラウンドロビン形式で行うか、なんらかのセマンティックなパーティション形式(つまり、メッセージ内のなんらかのキーに基づいて)に従ってすることができます。More on the use of partitioning in a second.

コンシューマ

メッセージングは伝統的に二つのモデルを持ちます: キューイング発行-購買。キュー内では、コンシュマーのプールはサーバから読み込むかもしれません。各メッセージはそれらのうちの一つに行きます; 発行-購読の中で、メッセージは全てのコンシューマにブロードキャストされます。Kafkaはそれらの両方を一般化した1つのコンシューマの抽象を提供します。 コンシューマ グループ

Consumers label themselves with a consumer group name, and each message published to a topic is delivered to one consumer instance within each subscribing consumer group. コンシューマーインスタンスは別個のプロセスの中あるいは別個のマシーン上にあるかも知れません。

全てのコンシューマインスタンスが同じコンシューマグループを持つ場合、これはコンシューマ上の伝統的なキューバランシング ロードバランサと同じ働きをします。

全てのコンシューマインスタンスが異なるコンシューマグループを持つ場合、これは発行-購買と同じ働きをし、全てのメッセージはすべてのコンシューマにブロードキャストされます。

More commonly, however, we have found that topics have a small number of consumer groups, one for each "logical subscriber". 各グループはスケーラビリティと耐障害性のために多くのコンシューマインスタンスから成ります。これは、サブスクライバーが1つのプロセスの代わりにコンシューマのクラスタである、発行-購買セマンティクスに他なりません。


二つのコンシューマグループを持つ4つのパーティション (P0-P3) をホストしている2つのサーバのKafkaクラスタ。コンシューマグループ A は二つのコンシューマインスタンスを持ち、グループBは4つを持ちます。

Kafka は伝統的なメッセージングシステムよりも強力な順番の保証も持ちます。

伝統的なキューはサーバ上で順番でメッセージを保持し、もし複数のコンシューマがキューから消費すると、サーバは格納しているメッセージを順番に分配します。しかし、サーバはメッセージを順番に分配しますが、メッセージは非同期でコンシューマに配送されます。そのためそれらは異なるコンシューマ上で順番がばらばらで到着するかも知れません。これは並行消費の前ではメッセージの順番は事実上失われることを意味します。メッセージングシステムはしばしば1つのプロセスのみがキューから消費することができる"排他コンシューマー"という概念を持つことでこれに対処しますが、もちろんこれは処理中に並行度が無いことを意味します。

Kafkaはそれをもうちょっとうまくやります。トピック内の並行度の概念 - パーティション - を持つことで、Kafkaは順番の保証とコンシューマのプロセスのプール上のロードバランシングの両方を提供することができます。これはトピック内のパーティションを、各パーティションがグループ内の確実に1つのコンシューマによって消費されるように、コンシューマグループ内のコンシューマに割り当てることで達成されます。こうすることで、コンシューマがパーティション内の唯一のreaderであることを確実にし、順番にデータを消費することを確実にします。多くのパーティションがあるので、これは多くのコンシューマのインスタンス上で負荷のバランスを取ります。しかし、コンシューマグループ内のコンシューマインスタンスはパーティションの数よりも大きくできないことに注意してください。

Kafkaはパーティションのメッセージ上の全体の順番のみを提供し、トピック内の異なるパーティション間では提供しません。Per-partition ordering combined with the ability to partition data by key is sufficient for most applications. However, if you require a total order over messages this can be achieved with a topic that has only one partition, though this will mean only one consumer process per consumer group.

保証

高レベルにおいて、Kafkaは以下の保証を与えます: これらの保証についての詳細はドキュメントの設計の章で見つけることができます。

1.2ユースケース

以下はApache Kafkaの人気のある使い方の2,3の説明です。これらの領域で活動中の多くの概要については、このブログの投稿を見てください。

メッセージング

Kafka は伝統的なメッセージブローカーの代替として良く動作します。メッセージブローカーは様々な理由で使われます (データプロデューサからの処理の切り離し、未処理メッセージのバッファ、など)。ほとんどのメッセージングシステムと比較してKafkaはより良いスループット、組み込みのパーティショニング、リプリケーション、および大規模メッセージ処理アプリケーションのための良い解決法となる耐障害性を持ちます。

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.

この領域において、KafkaはActiveMQ あるいは RabbitMQのような伝統的なメッセージングシステムと互換性があります。

Webサイト アクティビティ追跡

Kafkaの元のユースケースはリアルタイム発行-購読フィードのセットとしてユーザのアクティビティトラッキング パイプラインを再構築できるようにすることです。これは、サイトアクティビティ(ページビュー、検索、あるいはユーザが取るかも知れない他のアクション)がアクティビティタイプごとに1つのトピックを持つ中核トピックへ発行されることを意味します。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.

多くのアクティビティメッセージが各ユーザページビューに対して保証されるので、アクティビティトラッキングはしばしば大きなものになります。

マトリックス

Kafka はしばしば操作の監視データのために使われます。This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.

ログの集約

多くの人がKafkaをログ集約の解決法として使います。ログ集約は一般的に物理的なログファイルをサーバから離れて集め、それらを中核の場所(ファイルサーバあるいはHDFSおそらく)に処理のために配置します。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 published the cleansed article content to a new topic; a final processing stage might attempt to recommend this content to users. そのような処理パイプラインは各トピックに基づいたリアルタイムデータフローのグラフを生成します。上で述べたようなデータ処理を行うためにApache Kafkaでは0.10.0.0からKafka Streamsと呼ばれる軽量だが強力なストリーム処理ライブラリが利用可能です。Kafkaストリームは別として、代替となるオープンソースストリーム処理ツールは Apache StormApache Samzaを含みます。

イベント ソーシング

イベント ソーシング は状態の変化がレコードの時間順のシーケンスとして記録されるアプリケーション設計の形式です。とても大きな格納ログデータのためのKafkaのサポートは、この形式で構築されたアプリケーションのための洗練されたバックエンドになります。

コミットログ

Kafkaは分散型システムのための外部コミットログの一種として提供することができます。ログはノード間のデータのリプリケートを助け、障害ノードがデータを復旧するための再同期の仕組みとして振る舞います。Kafkaのログ コンパクション 機能はこの使い方をサポートします。この使い方において、KafkaはApache BookKeeper プロジェクトに似ています。

1.3クイックスタート

このチュートリアルでは、あなたは新しく始めて既存のKafkaあるいはZooKeeperデータが無いと仮定します。

ステップ 1: コードのダウンロード

0.10.0.0 リリースをダウンロードし、それをun-tarします。
> tar -xzf kafka_2.11-0.10.0.0.tgz
> cd kafka_2.11-0.10.0.0

ステップ 2: サーバの開始

Kafka は ZooKeeperを使います。そのためまだZooKeeperが無い場合はそれを最初に開始する必要があります。quick-and-dirty single-node ZooKeeper インスタンスを取得するためにKafkaにパッケージ化されている便利なスクリプトを使うことができます。

> bin/zookeeper-server-start.sh config/zookeeper.properties
[2013-04-22 15:01:37,495] INFO Reading configuration from: config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)
...
これでKafkaサーバを開始します:
> bin/kafka-server-start.sh config/server.properties
[2013-04-22 15:01:47,028] INFO Verifying properties (kafka.utils.VerifiableProperties)
[2013-04-22 15:01:47,051] INFO Property socket.send.buffer.bytes is overridden to 1048576 (kafka.utils.VerifiableProperties)
...

ステップ 3: トピックの作成

1つのパーティションと1つのレプリカだけを持つ"test"という名前のトピックを作成しましょう:
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
これで list トピックコマンドを実行するとトピックを見ることができます:
> bin/kafka-topics.sh --list --zookeeper localhost:2181
test
別のやり方として、手動でトピックを作成する代わりに、既存に無いトピックが発行された場合にブローカーがトピックを自動生成するように設定することもできます。

ステップ 4: メッセージを送信

Kafka はファイルあるいは標準入力から入力を受け取りそれをメッセージとしてKafkaクラスタに送信するコマンドライン クライアントが付属しています。デフォルトで各行は別個のメッセージとして送信されるでしょう。

プロデューサを実行し、その後サーバに送信するために2,3のメッセージをコンソールに入力します。

> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
This is a message
This is another message

ステップ 5: コンシューマの開始

Kafka はメッセージを標準出力に出力するコマンドラインコンシューマも持ちます。
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning
This is a message
This is another message

上のコマンドのそれぞれを異なるターミナル内で実行する場合、プロデューサターミナル内にメッセージを入力することができ、それらがコンシューマターミナル内に現れるのを見るでしょう。

コマンドラインツールの全ては追加のオプションを持ちます; 引数無しのコマンドの実行は使い方のもっと詳しい説明を表示するでしょう。

ステップ 6: 複数のブローカークラスタのセットアップ

これまでのところ1つのブローカーを実行してきましたが、それは楽しくありません。Kafkaにとっては1つのブローカーはサイズが1のクラスタなので、ある程度のブローカーインスタンスを開始する以外の何も違いはありません。しかし、それを感じるために、クラスタを3つのノードに拡張してみましょう (まだ全てがローカルのマシーン上にあります)。

まず、各ブローカーのための設定を作ります:

> cp config/server.properties config/server-1.properties
> cp config/server.properties config/server-2.properties
今度はこれらの新しいファイルを編集し以下のプロパティを設定します:

config/server-1.properties:
    broker.id=1
    listeners=PLAINTEXT://:9093
    log.dir=/tmp/kafka-logs-1

config/server-2.properties:
    broker.id=2
    listeners=PLAINTEXT://:9094
    log.dir=/tmp/kafka-logs-2
broker.id プロパティは、クラスタ内の各ノードのユニークで恒久的な名前です。We have to override the port and log directory only because we are running these all on the same machine and we want to keep the brokers from all trying to register on the same port or overwrite each others data.

すでにZookeeperがあり1つのノードを開始しているため、二つの新しいノードを開始する必要があります:

> bin/kafka-server-start.sh config/server-1.properties &
...
> bin/kafka-server-start.sh config/server-2.properties &
...
今度は3つのリプリケーション ファクターを持つ新しいトピックを作成します:
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 1 --topic my-replicated-topic
これで良いですが、今はクラスタがあるのでどうやってどのブローカーが何をしているのかを知ることができますか?To see that run the "describe topics" command:
> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic	PartitionCount:1	ReplicationFactor:3	Configs:
	Topic: my-replicated-topic	Partition: 0	Leader: 1	Replicas: 1,2,0	Isr: 1,2,0
ここからが出力の解説です。最初の行は全てのパーティションの概要を与え、各追加の行は1つのパーティションの情報を与えます。このトピックについて1つのパーティションのみを持つため、1つの行しかありません。 例では、ノード1がトピックの唯一のパーティションのためのリーダーであることに注意してください。

We can run the same command on the original topic we created to see where it is:

> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test
Topic:test	PartitionCount:1	ReplicationFactor:1	Configs:
	Topic: test	Partition: 0	Leader: 0	Replicas: 0	Isr: 0
So there is no surprise there—the original topic has no replicas and is on server 0, the only server in our cluster when we created it.

新しいトピックに2,3のメッセージを発行してみましょう:

> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my-replicated-topic
...
my test message 1
my test message 2
^C
今度はこれらのメッセージを消費してみましょう:
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic my-replicated-topic
...
my test message 1
my test message 2
^C
今度は耐障害性を試してみましょう。ブローカー1はリーダーとして振る舞っていました。そういうわけでそれをkillしましょう:
> ps | grep server-1.properties
7564 ttys002    0:15.91 /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java...
> kill -9 7564
リーダーシップはスレーブの一つに切り替わり、ノード1はin-syncレプリカセットの中にはもういません:
> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic	PartitionCount:1	ReplicationFactor:3	Configs:
	Topic: my-replicated-topic	Partition: 0	Leader: 2	Replicas: 1,2,0	Isr: 2,0
しかし、もともと書き込んだリーダーがダウンしたにも関わらず、メッセージはまだ消費可能です:
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic my-replicated-topic
...
my test message 1
my test message 2
^C

ステップ 7: データをインポート/エクスポートするためにKafka Connectを使用

コンソールからデータを書き込み、コンソールに書き込み返すのは始めるのに具合が良いですが、おそらく他のソースからのデータを使うかKafkaから他のシステムへデータをエクスポートしたいでしょう。多くのシステムについて、データをインポートあるいはエクスポートするために独自の統合コードを書く代わりにKafka Connectを使うことができます。Kafka Connect はKafkaにデータをインポートあるいはエクスポートするKafkaに含まれているツールです。connectorsを実行する拡張ツールで、外部システムと相互作用するための独自のロジックを実装します。このクイックスタートの中で、ファイルからKafkaトピックへデータをインポートしKafkaトピックからファイルへデータをエクスポートする単純なコネクタを使ってKafka Connectを実行する方法を見ます。まず、テストするためのいくつの種のデータを作成することで始めます:
> echo -e "foo\nbar" > test.txt
次に、スタンドアローン モードで実行中の二つのコネクタを開始します。これは1つのローカルの専用のプロセス内で実行することを意味します。パラメータとして3つの設定ファイルを与えます。The first is always the configuration for the Kafka Connect process, containing common configuration such as the Kafka brokers to connect to and the serialization format for data. 残りの設定ファイルはそれぞれ生成するコネクタを指定します。これらのファイルはユニークなコネクタ名、インスタンス化するコネクタクラス、およびコネクタによって必要とされるその他の設定を含みます。
> bin/connect-standalone.sh config/connect-standalone.properties config/connect-file-source.properties config/connect-file-sink.properties
これらの例の設定ファイルは、Kafkaに含まれ、前に開始したデフォルトのローカルクラスタの設定を使用し、二つのコネクタを生成します: 1つ目のコネクタは入力ファイルから行を読み込むソースコネクタで、Kafkaトピックにそれぞれを生成します。二つ目のコネクタはKafkaトピックからメッセージを読み込み、出力ファイル中に行としてそれぞれを生成するシンクコネクタです。スタートアップの間に、コネクタがインスタンス化されたことを示す多くのログメッセージを見るでしょう。Kafka Connect プロセスが一度開始されると、ソースコネクタは以下から行を読み始めている筈です
test.txt
そして、それらをトピックに生成します。
connect-test
そして、シンクコネクタがトピックからメッセージを読み始めている筈です。
connect-test
そして、それらをファイルに書き込みます。
test.sink.txt
. 出力ファイルの内容を調べることでパイプライン全体を通して配送されるデータを検証することができます。
> cat test.sink.txt
foo
bar
データはKafkaトピックに格納されていることに注意してください。
connect-test
つまり、トピック内のデータを見るためにコンソールのコンシューマを実行することもできます (あるいはそれを処理するために独自のコンシューマコードを使います):
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic connect-test --from-beginning
{"schema":{"type":"string","optional":false},"payload":"foo"}
{"schema":{"type":"string","optional":false},"payload":"bar"}
...
コネクタはデータを処理しつづけます。つまり、データをファイルに追加しパイプラインを使って移動するのを見ることができます:
> echo "Another line" >> test.txt
コンシューマ出力のコンソール内とシンクファイル内に行が現れるのが見えるはずです。

ステップ 8: データを処理するためにKafkaストリームを使う

Kafka Streams はリアルタイム ストリーム処理とKafkaブローカー内に格納されているデータの解析のためのKafkaのクライアントライブラリです。このクイックスタートの例はこのライブラリ内でコードされたストリーミングアプリケーションを実行する方法を説明するでしょう。これは WordCountDemo の例のコードの要旨です (読みやすいようにJava 8 lamda表現を使うように変換されています)。

KTable wordCounts = textLines
    // Split each text line, by whitespace, into words.
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))

    // Ensure the words are available as record keys for the next aggregate operation.
    .map((key, value) -> new KeyValue<>(value, value))

    // Count the occurrences of each word (record key) and store the results into a table named "Counts".
    .countByKey("Counts")

WordCount アルゴリズムを実装しています。これは入力テキストから単語の出現ヒストグラムを計算します。しかし、あなたがこれまで見てきたような有限データ上で操作するWordCountの例と異なり、WordCoundデモアプリケーションは 無限、制限のないストリームのデータ上での操作をするように設計されているため、わずかに異なる挙動をします。有限の変異種に似て、それは単語の数を追跡および更新するステートフルなアルゴリズムです。しかし、無限の入力データの可能性があると仮定しなければならないため、"全ての"入力データが処理されたかを知ることができないため、データを処理している間は現在の状態と結果を定期的に出力するでしょう。

これでKafkaトピックへの入力データを準備できるでしょう。これは後でKafkaストリームアプリケーションによって処理されるでしょう。

> echo -e "all streams lead to kafka\nhello kafka streams\njoin kafka summit" > file-input.txt

次に、コンソールプロデューサを使ってstreams-file-input という名前の入力トピックへこの入力データを送信します (実際問題として、ストリームデータはアプリケーションが作動して実行しているKafkaへ連続して流れ込む可能性が高いです):

> cat /tmp/file-input.txt | ./bin/kafka-console-producer --broker-list localhost:9092 --topic streams-file-input

これで入力データを処理するためにWordCountデモアプリケーションを実行することができます:

> ./bin/kafka-run-class org.apache.kafka.streams.examples.wordcount.WordCountDemo

There won't be any STDOUT output except log entries as the results are continuously written back into another topic named streams-wordcount-output in Kafka. デモは数秒の間実行し、代表的なストリーミング処理アプリケーションと異なり自動的に終了するでしょう。

これで出力トピックから読み込むことでWordCountデモアプリケーションの出力を調べることができます:

> ./bin/kafka-console-consumer --zookeeper localhost:2181 \
            --topic streams-wordcount-output \
            --from-beginning \
            --formatter kafka.tools.DefaultMessageFormatter \
            --property print.key=true \
            --property print.key=true \
            --property key.deserializer=org.apache.kafka.common.serialization.StringDeserializer \
            --property value.deserializer=org.apache.kafka.common.serialization.LongDeserializer

with the following output data being printed to the console (You can stop the console consumer via Ctrl-C):

all     1
streams 1
lead    1
to      1
kafka   1
hello   1
kafka   2
streams 2
join    1
kafka   3
summit  1
^C

ここで、最初のカラムはKafkaメッセージキーで、二つ目のカラムはメッセージの値です。両方ともjava.lang.String 形式です。出力は実は更新の連続するストリームです。ここで、各データのレコード(別の言い方をすると上の元の出力の各行)は1つの単語の更新されたカウント、"kafka"のような別名のレコードキーです。同じキーの複数のレコードについては、それぞれの後者のレコードが前者のレコードを更新します。

1.4エコシステム

メインの配布物の他にKafkaを使って統合する有り余るほどのツールがあります。エコシステムのページはこれらの多くをリスト化し、ストリーム処理システム、Hadoop統合、監視および開発ツールを含みます。

1.5以前のバージョンからのアップグレード

0.8.x あるいは 0.9.x から 0.10.0.0 へのアップグレード

0.10.0.0 は 破壊的な変更の可能性 (アップグレードの前に再調査してください)があり、アップグレードの間にパフォーマンスの問題があるかも知れません。新しいプロトコルが導入されたため、クライアントをアップグレードする前にKafkaクラスタをアップグレードすることが重要です。

Notes to clients with version 0.9.0.0: Due to a bug introduced in 0.9.0.0, clients that depend on ZooKeeper (old Scala high-level Consumer and MirrorMaker if used with the old consumer) will not work with 0.10.0.x brokers. 従って 0.9.0.0 クライアントはブローカーが 0.10.0.x にアップグレードされる前に 0.9.0.1 にアップグレードされる必要があります。このステップは、0.8.X あるいは 0.9.0.1 クライアントの場合には必要ありません。

ローリングアップグレードに関して:

  1. 全てのブローカー上の server.properties ファイルをアップデートし、以下のプロパティを追加してください: inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例えば、 0.8.2 あるいは 0.9.0.0)。We recommend that users set log.message.format.version=CURRENT_KAFKA_VERSION as well to avoid a performance regression during upgrade. 詳細は アップグレード中のパフォーマンス影響の可能性 を見てください。
  2. ブローカーのアップグレード。単純にブローカーをダウンし、コードを更新し、再起動することで一度に行うことができます。
  3. クラスタ全体がアップグレードされると、inter.broker.protocol.version を編集し 0.10.0.0 に設定することでプロトコルのバージョンを上げることができます。
  4. 新しいプロトコルのバージョンが効果を現すようにブローカーを1つずつ再起動します。

注意: ダウンタイムを喜んで許容する場合は、単純に全てのブローカーをダウンし、コードを更新し、それら全てを開始します。それらはデフォルトで新しいプロトコルを使って開始するでしょう。

注意: プロトコルのバージョンアップと再起動はブローカーがアップグレードされた後でいつでも行うことができます。すぐにしなければならないことはありません。

0.10.0.0 へのアップグレード時にパフォーマンスの影響の可能性があります。

0.10.0 でのメッセージフォーマットは新しいタイムスタンプのフィールドを含み、圧縮されたメッセージのための相対的なオフセットを使います。ディスク上のメッセージフォーマットは server.properties ファイル内の log.message.format.version を使って設定することができます。デフォルトのディスク上のメッセージフォーマットは 0.10.0 です。0.10.0.0より前のコンシューマクライアントがいる場合は、0.10.0より前のメッセージフォーマットのみを理解します。この場合、ブローカーは古いバージョン上のコンシューマへメッセージを送信する前に、メッセージを0.10.0のフォーマットから以前のフォーマットに変換することができます。しかし、ブローカーはこの場合 ゼロコピー転送を使うことができません。コンシューマが0.10.0.0にアップグレードされる前にそのようなメッセージの変換を避けるために、ブローカーを0.10.0.0にアップグレードする時にメッセージフォーマットを例えば0.9.0にT設定することができます。このようにブローカーはデータを古いコンシューマに送信するためにまだzero-copyを使うことができます。ほとんどのコンシューマがアップグレードされると、ブローカー上でメッセージフォーマットを0.10.0に変更することができます。

0.10.0.0にアップグレードされたクライアントについては、パフォーマンスの影響はありません。

注意: メッセージフォーマットのバージョンを設定することで、既存の全てのメッセージはそのメッセージフォーマットのバージョン以下であると保証します。そうでなければ、0.10.0.0より前のコンシューマが壊れるかも知れません。特に、メッセージフォーマットが0.10.0に設定された後で、0.10.0.0より前のバージョンのコンシューマを壊すかも知れないので以前のフォーマットに戻す変更をするべきではありません。

注意: 各メッセージ内に導入された追加のタイムスタンプによって、小さなメッセージを送信しているプロデューサはオーバーヘッドの増加によりメッセージのスループットの減少を経験するかもしれません。さらに、リプリケーションは今度はメッセージごとに追加の8バイトを転送します。もしクラスタのネットワーク許容量すれすれで実行している場合は、ネットワークカードを圧倒し過負荷による障害とパフォーマンスの問題に遭遇するでしょう。

Note: If you have enabled compression on producers, you may notice reduced producer throughput and/or lower compression rate on the broker in some cases. 圧縮されたメッセージを受け取る場合、0.10.0ブローカーはメッセージの圧縮を避けます。この事は一般的にレイテンシーを下げ、スループットを改善します。しかし、特定の場合において、これはプロデューサ上のバッチのサイズを削減するかも知れません。このことはスループットの改悪につながるかも知れません。これが起きた場合は、ユーザはより良いスループットのためにプロデューサのlinger.msとbatch.sizeを調整することができます。さらに、snappyを使ってメッセージを圧縮するために使われるプロデューサのバッファは、ブローカーによって使われるものよりも小さくなります。これはディスク上のメッセージの圧縮レートへの負の衝撃を持つかも知れません。将来のKafkaリリースではこれを設定可能にするつもりです。

0.10.0.0での破壊的な変更の可能性
0.10.0.0 での主要な変更

0.8.0, 0.8.1.X あるいは 0.8.2.X から 0.9.0.0 へのアップグレード

0.9.0.0 は破壊的な変更の可能性 (アップグレードする前に精査してください)があり、以前のバージョンからのブローカー間のプロトコルの変更があります。このことはアップグレードされたブローカーとクライアントは古いバージョンと互換性が無いかも知れないことを意味します。クライアントをアップグレードする前にKafkaクラスタをアップグレードすることが重要です。MirrorMaker ダウンストリームを使っている場合は、クラスタも同様に最初にアップグレードされるべきです。

ローリングアップグレードに関して:

  1. 全てのブローカー上の server.properties ファイルを更新し、以下のプロパティを追加します : inter.broker.protocol.version=0.8.2.X
  2. ブローカーのアップグレード。単純にブローカーをダウンし、コードを更新し、再起動することで一度に行うことができます。
  3. クラスタ全体がアップグレードされると、inter.broker.protocol.version を編集し 0.9.0.0 に設定することでプロトコルのバージョンを上げることができます。
  4. 新しいプロトコルのバージョンが効果を現すようにブローカーを1つずつ再起動します。

注意: ダウンタイムを喜んで許容する場合は、単純に全てのブローカーをダウンし、コードを更新し、それら全てを開始します。それらはデフォルトで新しいプロトコルを使って開始するでしょう。

注意: プロトコルのバージョンアップと再起動はブローカーがアップグレードされた後でいつでも行うことができます。すぐにしなければならないことはありません。

0.9.0.0での破壊的な変更の可能性
0.9.0.1 での主要な変更
0.9.0.0 での非推奨

0.8.1 から 0.8.2 へのアップグレード

0.8.2 は 0.8.1 と完全に互換性があります。単純に1つのブローカーをダウンし、コードを更新し、再起動することで一度にアップグレードを行うことができます。

0.8.0 から 0.8.1 へのアップグレード

0.8.1 は 0.8 と完全に互換性があります。単純に1つのブローカーをダウンし、コードを更新し、再起動することで一度にアップグレードを行うことができます。

0.7からのアップグレード

リリース 0.7 は新しいリリースと互換性がありません。Major changes were made to the API, ZooKeeper data structures, and protocol, and configuration in order to add replication (Which was missing in 0.7). 0.7から最新のバージョンへのアップグレードは移行のために 特別なツール を必要とします。この移行はダウンタイム無しで行うことができます。

2. API

Apache Kafka は新しい java クライアント を含みます (org.apache.kafka.clients パッケージ内)。These are meant to supplant the older Scala clients, but for compatibility they will co-exist for some time. 古いScalaクライアントはサーバにパッケージされますが、これらのクライアントは最小限の依存性を持って別のjarで利用可能です。

2.1プロデューサ API

全ての新しい開発で新しいJavaプロデューサを使うことをお勧めします。このクライアントはプロダクションでテストされ、一般的に以前のScalaのクライアントよりも高速でもっと高機能です。You can use this client by adding a dependency on the client jar using the following example maven co-ordinates (you can change the version numbers with new releases):
	<dependency>
	    <groupId>org.apache.kafka</groupId>
	    <artifactId>kafka-clients</artifactId>
	    <version>0.10.0.0</version>
	</dependency>
プロデューサをどう使うかを示す例がjavadocsにあります。

従来のScala プロデューサAPIに興味がある人のために、ここで情報を見つけることができます。

2.2コンシューマ API

0.9.0 リリースの時点で、既存の高レベル ZooKeeperに基づいたコンシューマと低レベルのコンシューマーAPIを置き換えるために新しいJavaコンシューマを追加しました。このクライアントはベータ品質と見なされます。ユーザにとってスムーズなアップグレードの方法を保証するために、0.9 Kafkaクラスタ上で動作し続けるまだ古い0.8コンシューマクライアントを維持します。以下のセクションでは、古い0.8コンシューマAPI(高レベル ConsumerConnector と 低レベル SimpleConsumer) と、新しいJavaコンシューマAPIをそれぞれ紹介します。

2.2.1古い高レベルコンシューマ API

class Consumer {
  /**
   *  Create a ConsumerConnector
   *
   *  @param config  at the minimum, need to specify the groupid of the consumer and the zookeeper
   *                 connection string zookeeper.connect.
   */
  public static kafka.javaapi.consumer.ConsumerConnector createJavaConsumerConnector(ConsumerConfig config);
}

/**
 *  V: type of the message
 *  K: type of the optional key associated with the message
 */
public interface kafka.javaapi.consumer.ConsumerConnector {
  /**
   *  Create a list of message streams of type T for each topic.
   *
   *  @param topicCountMap  a map of (topic, #streams) pair
   *  @param decoder a decoder that converts from Message to T
   *  @return a map of (topic, list of  KafkaStream) pairs.
   *          The number of items in the list is #streams. Each stream supports
   *          an iterator over message/metadata pairs.
   */
  public <K,V> Map<String, List<KafkaStream<K,V>>>
    createMessageStreams(Map<String, Integer> topicCountMap, Decoder<K> keyDecoder, Decoder<V> valueDecoder);

  /**
   *  Create a list of message streams of type T for each topic, using the default decoder.
   */
  public Map<String, List<KafkaStream<byte[], byte[]>>> createMessageStreams(Map<String, Integer> topicCountMap);

  /**
   *  Create a list of message streams for topics matching a wildcard.
   *
   *  @param topicFilter a TopicFilter that specifies which topics to
   *                    subscribe to (encapsulates a whitelist or a blacklist).
   *  @param numStreams the number of message streams to return.
   *  @param keyDecoder a decoder that decodes the message key
   *  @param valueDecoder a decoder that decodes the message itself
   *  @return a list of KafkaStream. Each stream supports an
   *          iterator over its MessageAndMetadata elements.
   */
  public <K,V> List<KafkaStream<K,V>>
    createMessageStreamsByFilter(TopicFilter topicFilter, int numStreams, Decoder<K> keyDecoder, Decoder<V> valueDecoder);

  /**
   *  Create a list of message streams for topics matching a wildcard, using the default decoder.
   */
  public List<KafkaStream<byte[], byte[]>> createMessageStreamsByFilter(TopicFilter topicFilter, int numStreams);

  /**
   *  Create a list of message streams for topics matching a wildcard, using the default decoder, with one stream.
   */
  public List<KafkaStream<byte[], byte[]>> createMessageStreamsByFilter(TopicFilter topicFilter);

  /**
   *  Commit the offsets of all topic/partitions connected by this connector.
   */
  public void commitOffsets();

  /**
   *  Shut down the connector
   */
  public void shutdown();
}

高レベルコンシューマAPIを使う方法を学ぶために、この例 に従うことができます。

2.2.2古いシンプルコンシューマAPI

class kafka.javaapi.consumer.SimpleConsumer {
  /**
   *  Fetch a set of messages from a topic.
   *
   *  @param request specifies the topic name, topic partition, starting byte offset, maximum bytes to be fetched.
   *  @return a set of fetched messages
   */
  public FetchResponse fetch(kafka.javaapi.FetchRequest request);

  /**
   *  Fetch metadata for a sequence of topics.
   *
   *  @param request specifies the versionId, clientId, sequence of topics.
   *  @return metadata for each topic in the request.
   */
  public kafka.javaapi.TopicMetadataResponse send(kafka.javaapi.TopicMetadataRequest request);

  /**
   *  Get a list of valid offsets (up to maxSize) before the given time.
   *
   *  @param request a [[kafka.javaapi.OffsetRequest]] object.
   *  @return a [[kafka.javaapi.OffsetResponse]] object.
   */
  public kafka.javaapi.OffsetResponse getOffsetsBefore(OffsetRequest request);

  /**
   * Close the SimpleConsumer.
   */
  public void close();
}
ほとんどのアプリケーションにとって、高レベルコンシューマAPIで十分です。Some applications want features not exposed to the high level consumer yet (e.g., set initial offset when restarting the consumer). それらは代わりに低レベルSimpleConsumer Apiを使うことができます。ロジックは多少複雑ですが、ここの例に従うことができます。

2.2.3新しいコンシューマAPI

この新しい統一されたコンシューマAPIは0.8高レベルと低レベルコンシューマAPIの間の区別を取り去ります。You can use this client by adding a dependency on the client jar using the following example maven co-ordinates (you can change the version numbers with new releases):
	<dependency>
	    <groupId>org.apache.kafka</groupId>
	    <artifactId>kafka-clients</artifactId>
	    <version>0.10.0.0</version>
	</dependency>
コンシューマをどう使うかを示す例がjavadocsにあります。

2.3ストリーム API

0.10.0 リリースの時点で、ユーザがKafkaトピックスの中に格納されたデータを使ってストリーム処理アプリケーションを実装することができるKafka Streams という名前の新しいクライアントライブラリを追加しました。Kafka ストリームはアルファクオリティと見なされ、公開されているAPIは将来のリリースで変更されるかもしれません。You can use Kafka Streams by adding a dependency on the streams jar using the following example maven co-ordinates (you can change the version numbers with new releases):
	<dependency>
	    <groupId>org.apache.kafka</groupId>
	    <artifactId>kafka-streams</artifactId>
	    <version>0.10.0.0</version>
	</dependency>
Examples showing how to use this library are given in the javadocs (note those classes annotated with @InterfaceStability.Unstable, indicating their public APIs may change without backward-compatibility in future releases).

3. 設定

Kafka は設定のためにプロパティ ファイル形式のキー-値ペアを使います。これらの値はファイルまたはプログラムのどちらかで提供することができます。

3.1ブロッカーの設定

重要な設定は以下の通りです: トピックレベルの設定とデフォルトは以下でもっと詳細に議論されます。
名前 解説 種類 デフォルト 有効な値 重要性
zookeeper.connectZookeeper ホスト文字列stringhigh
advertised.host.name非推奨: `advertised.listeners` または `listeners` が設定されていない場合にのみ使われます。代わりに `advertised.listeners`を使ってください。クライアントが使うためにZooKeeperに公開されるホスト名。IaaS 環境では、これはブローカーがバインドするインタフェースとは異なる必要があるかも知れません。これが設定されない場合、設定されていれば`host.name` の値が使われるでしょう。そうでなければ、java.net.InetAddress.getCanonicalHostName() から返される値を使うでしょう。stringnullhigh
advertised.listeners上のリスナーと異なる場合、クライアントが使用するZooKeeperに公開されるリスナー。IaaS 環境では、これはブローカーがバインドするインタフェースとは異なる必要があるかも知れません。これが設定されない場合は、`listeners`の値が使われるでしょう。stringnullhigh
advertised.port非推奨: `advertised.listeners` または `listeners` が設定されていない場合にのみ使われます。代わりに `advertised.listeners`を使ってください。クライアントが使用するZooKeeperへ公開されるポート。IaaS 環境では、これはブローカーがバインドするポートとは異なる必要があるかも知れません。設定されない場合は、ブローカーがバインドする同じポートを公開するでしょう。intnullhigh
auto.create.topics.enableサーバ上でのトピックの自動生成を有効booleantruehigh
auto.leader.rebalance.enable自動リーダーバランシングを有効にする。A background thread checks and triggers leader balance if required at regular intervalsbooleantruehigh
background.threads様々なバックグラウンド処理タスクが使うスレッドの数int10[1,...]high
broker.idこのサーバのためのブローカーid。If unset, a unique broker id will be generated.To avoid conflicts between zookeeper generated broker id's and user configured broker id's, generated broker idsstart from reserved.broker.max.id + 1.int-1high
compression.type指定されたトピックのための最終的な圧縮タイプを指定する。この設定は標準的な圧縮コーディック('gzip', 'snappy', 'lz4')を受け付けます。It additionally accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the original compression codec set by the producer.stringproducerhigh
delete.topic.enableトピックの削除を有効にする。この設定が切られている場合は管理ツールを使ったトピックの削除は何も効果が無いでしょう。booleanfalsehigh
host.name非推奨: `listeners` が設定されていない場合にのみ使われます。代わりに `listeners` を使ってください。ブローカーのホスト名。これが設定されている場合は、このアドレスへのみバインドするでしょう。これが設定されていない場合は、全てのインタフェースにバインドするでしょう。string""high
leader.imbalance.check.interval.secondsThe frequency with which the partition rebalance check is triggered by the controllerlong300high
leader.imbalance.per.broker.percentageブローカーあたりに許可されるリーダーの非バランスの割合。ブローカー毎にこの値を超えた場合は、コントローラーはリーダーのバランスを開始するでしょう。値はパーセンテージで指定されます。int10high
listenersListener List - Comma-separated list of URIs we will listen on and their protocols. 全てのインタフェースにバインドするためには 0.0.0.0 としてホスト名を指定してください。デフォルトのインタフェースにバインドするには、ホスト名を空にします。一般的なリスナーの例: PLAINTEXT://myhost:9092,TRACE://:9091 PLAINTEXT://0.0.0.0:9092, TRACE://localhost:9093 stringnullhigh
log.dirログデータが保持されるディレクトリ (log.dirs プロパティの補足)string/tmp/kafka-logshigh
log.dirsログデータが保持されるディレクトリ。設定しない場合は、log.dirの値が使われますstringnullhigh
log.flush.interval.messagesメッセージがディスクにフラッシュされる前にログパーティション上で集約されるメッセージの数 long9223372036854775807[1,...]high
log.flush.interval.msメモリ内に保持されたメッセージがディスクにフラッシュされるまでの最大ms。設定されていない場合は、log.flush.scheduler.interval.ms の値が使われます。longnullhigh
log.flush.offset.checkpoint.interval.msThe frequency with which we update the persistent record of the last flush which acts as the log recovery pointint60000[0,...]high
log.flush.scheduler.interval.msThe frequency in ms that the log flusher checks whether any log needs to be flushed to disklong9223372036854775807high
log.retention.bytesログが削除されるまでの最大サイズ。long-1high
log.retention.hoursThe number of hours to keep a log file before deleting it (in hours), tertiary to log.retention.ms propertyint168high
log.retention.minutesThe number of minutes to keep a log file before deleting it (in minutes), secondary to log.retention.ms property. 設定しない場合は、log.retention.hours の値が使われます。intnullhigh
log.retention.msログファイルが削除されるまでに保持されるミリ秒数。設定されない場合は、log.retention.minutes の値が使われます。longnullhigh
log.roll.hoursThe maximum time before a new log segment is rolled out (in hours), secondary to log.roll.ms propertyint168[1,...]high
log.roll.jitter.hoursThe maximum jitter to subtract from logRollTimeMillis (in hours), secondary to log.roll.jitter.ms propertyint0[0,...]high
log.roll.jitter.msThe maximum jitter to subtract from logRollTimeMillis (in milliseconds). 設定しない場合は、log.roll.jitter.hours の値が使われますlongnullhigh
log.roll.ms新しいログの断片がロールアウトされるまでの最大時間(ミリ秒)。設定しない場合は、log.roll.hours の値が使われますlongnullhigh
log.segment.bytes1つのログファイルの最大サイズint1073741824[14,...]high
log.segment.delete.delay.msファイルシステムからファイルを削除するまでの総待ち時間long60000[0,...]high
message.max.bytesサーバが受け取ることができるメッセージの最大サイズint1000012[0,...]high
min.insync.replicasdefine the minimum number of replicas in ISR needed to satisfy a produce request with acks=all (or -1)int1[1,...]high
num.io.threadsネットワークリクエストを発行するためにサーバが使用するioスレッドの数。int8[1,...]high
num.network.threadsネットワークリクエストを処理するためにサーバが使用するネットワークスレッドの数。int3[1,...]high
num.recovery.threads.per.data.dir起動時のログの回復とシャットダウン時にフラッシュするために使われるデータディレクトリあたりのスレッドの数。int1[1,...]high
num.replica.fetchersソースブローカーからメッセージをリプリケートするために使われるフェッチスレッドの数。この値を増加することで追随するブローカーのI/O並行度の度合いを増やすことができます。int1high
offset.metadata.max.bytesオフセット コミットに関連するメタデータ エントリのための最大サイズ。int4096high
offsets.commit.required.acksコミットが受け付けられるまでに必要とされるack。通常はデフォルト(-1)を上書くべきではありませんshort-1high
offsets.commit.timeout.msOffset commit will be delayed until all replicas for the offsets topic receive the commit or this timeout is reached. これはプロデューサのリクエストタイムアウトに似ています。int5000[1,...]high
offsets.load.buffer.sizeオフセットをキャッシュにロードする時にオフセット セグメントから読み込むためのバッチサイズ。int5242880[1,...]high
offsets.retention.check.interval.msFrequency at which to check for stale offsetslong600000[1,...]high
offsets.retention.minutesオフセットトピックのためのログの保持ウィンドウの秒数int1440[1,...]high
offsets.topic.compression.codecオフセットトピックのための圧縮コーディック - 圧縮は "atomic" コミットを実現するために使われるかも知れませんint0high
offsets.topic.num.partitionsオフセット コミット トピックのためのパーティション数 (配備の後で変更すべきではありません)int50[1,...]high
offsets.topic.replication.factorオフセット トピックのためのリプリケーション要素 (可用性を保証するするために高く設定します)。To ensure that the effective replication factor of the offsets topic is the configured value, the number of alive brokers has to be at least the replication factor at the time of the first request for the offsets topic. If not, either the offsets topic creation will fail or it will get a replication factor of min(alive brokers, configured replication factor)short3[1,...]high
offsets.topic.segment.bytesThe offsets topic segment bytes should be kept relatively small in order to facilitate faster log compaction and cache loadsint104857600[1,...]high
port非推奨: `listeners` が設定されていない場合にのみ使われます。代わりに `listeners` を使ってください。the port to listen and accept connections onint9092high
queued.max.requestsネットワークスレッドをブロックするまでに許容されるリクエストのキューの数int500[1,...]high
quota.consumer.defaultAny consumer distinguished by clientId/consumer group will get throttled if it fetches more bytes than this value per-secondlong9223372036854775807[1,...]high
quota.producer.defaultAny producer distinguished by clientId will get throttled if it produces more bytes than this value per-secondlong9223372036854775807[1,...]high
replica.fetch.max.bytesThe number of bytes of messages to attempt to fetchint1048576high
replica.fetch.min.bytes各フェッチ応答に期待される最小バイト。十分なバイト数でなければ、replicaMaxWaitTimeMs まで待機しますint1high
replica.fetch.wait.max.ms随行するレプリカによって発行された各フェッチリクエストの最大待ち時間。This value should always be less than the replica.lag.time.max.ms at all times to prevent frequent shrinking of ISR for low throughput topicsint500high
replica.high.watermark.checkpoint.interval.msThe frequency with which the high watermark is saved out to disklong5000high
replica.lag.time.max.msIf a follower hasn't sent any fetch requests or hasn't consumed up to the leaders log end offset for at least this time, the leader will remove the follower from isrlong10000high
replica.socket.receive.buffer.bytesネットワークリクエストのためのソケット受信バッファint65536high
replica.socket.timeout.msネットワークリクエストのためのソケットタイムアウト。値は少なくとも replica.fetch.wait.max.ms でなければなりません。int30000high
request.timeout.msこの設定はクライアントがリクエストの応答を待つ総時間の最大を制御します。タイムアウトの時間が経過する前に応答が受信されない場合は、必要であればクライアントはリクエストを再送信するでしょう。あるいは再試行が使い尽くされた場合は失敗するでしょう。int30000high
socket.receive.buffer.bytesソケットサーバのソケットの SO_RCVBUF バッファint102400high
socket.request.max.bytesソケットリクエスト内の最大バイト数int104857600[1,...]high
socket.send.buffer.bytesソケットサーバのソケットの SO_SNDBUF バッファint102400high
unclean.leader.election.enableIndicates whether to enable replicas not in the ISR set to be elected as leader as a last resort, even though doing so may result in data lossbooleantruehigh
zookeeper.connection.timeout.msクライアントがzookeeperに接続を確立するまで待つ最大時間。設定しない場合は、zookeeper.session.timeout.ms の値が使われますintnullhigh
zookeeper.session.timeout.msZookeeper セッション タイムアウトint6000high
zookeeper.set.aclクライアントにsecure ACLを使うように設定しますbooleanfalsehigh
broker.id.generation.enableサーバ上で自動ブローカーid生成を有効にするWhen enabled the value configured for reserved.broker.max.id should be reviewed.booleantruemedium
broker.rackブローカーのラック。これはラックを気にするリプリケーションアサインメントで耐障害性のために使われます。例: `RACK1`, `us-east-1d`stringnullmedium
connections.max.idle.msアイドル接続タイムアウト: サーバソケットプロセッサ スレッドはこれより多いアイドルの接続を閉じますlong600000medium
controlled.shutdown.enableサーバの制御されたシャットダウンを有効にするbooleantruemedium
controlled.shutdown.max.retries制御されたシャットダウンは複数の理由で失敗するかも知れません。これはそのような障害が起きた時の再試行の数を決定しますint3medium
controlled.shutdown.retry.backoff.ms各再試行の前に、システムは以前の障害(コントローラのフェイルオーバー、ログのリプリカ)を起こす状態から回復するための時間が必要です。この設定は再試行の前に待つ総時間を決定します。long5000medium
controller.socket.timeout.msコントローラ-ブローカー チャンネルのためのソケットタイムアウトint30000medium
default.replication.factor自動的に生成されたトピックのためのデフォルトのリプリケーション要素int1medium
fetch.purgatory.purge.interval.requestsThe purge interval (in number of requests) of the fetch request purgatoryint1000medium
group.max.session.timeout.ms登録されたカスタマのための最大許可セッションタイムアウト。タイムアウトを長くすることでコンシューマは障害の検知までの長い時間を代償にハートビート間のメッセージの処理時間を長くします。int300000medium
group.min.session.timeout.ms登録されたカスタマのための最小許可セッションタイムアウト。Shorter timeouts leader to quicker failure detection at the cost of more frequent consumer heartbeating, which can overwhelm broker resources.int6000medium
inter.broker.protocol.versionどのバージョンの内部ブローカープロトコルが使われるかを指定します。これは一般的に全てのブローカーが新しいバージョンにアップグレードした後で取り消されます。有効ないくつかの値の例: 0.8.0, 0.8.1, 0.8.1.1, 0.8.2, 0.8.2.0, 0.8.2.1, 0.9.0.0, 0.9.0.1 完全なリストについては ApiVersion を調べてください。string0.10.0-IV1medium
log.cleaner.backoff.ms掃除するログが無い場合にスリープする総時間long15000[0,...]medium
log.cleaner.dedupe.buffer.size全てのクリーナースレッドを通じてログのデュプリケーションに使われる総メモリlong134217728medium
log.cleaner.delete.retention.msどれだけの期間削除されたレコードを保持するか?long86400000medium
log.cleaner.enableログクリーナープロセスをサーバ上で実行することを有効にするか?内部オフセットトピックを含む cleanup.policy=compact を使ってトピックを使う場合は有効にしなければなりません。無効にするとそれらのトピックはコンパクト化されずサイズが増加し続けるでしょう。booleantruemedium
log.cleaner.io.buffer.load.factorLog cleaner dedupe buffer load factor. The percentage full the dedupe buffer can become. A higher value will allow more log to be cleaned at once but will lead to more hash collisionsdouble0.9medium
log.cleaner.io.buffer.size全てのクリーナースレッドを通じてログ クリーナーのI/Oバッファに使われる総メモリint524288[0,...]medium
log.cleaner.io.max.bytes.per.secondThe log cleaner will be throttled so that the sum of its read and write i/o will be less than this value on averagedouble1.7976931348623157E308medium
log.cleaner.min.cleanable.ratioThe minimum ratio of dirty log to total log for a log to eligible for cleaningdouble0.5medium
log.cleaner.threadsログの掃除に使われるバックグラウンドスレッドの数int1[0,...]medium
log.cleanup.policyThe default cleanup policy for segments beyond the retention window, must be either "delete" or "compact"stringdelete[compact, delete]medium
log.index.interval.bytesオフセット インデックスにエントリを追加する間隔int4096[0,...]medium
log.index.size.max.bytesオフセット インデックスの最大バイト数int10485760[4,...]medium
log.message.format.versionブローカーがログにメッセージを追加する時に使うメッセージフォーマットを指定します。値は有効なApiVersionでなければなりません。いくつかの例: 0.8.2, 0.9.0.0, 0.10.0, 詳細はApiVersionを調べてください。特定のメッセージフォーマットバージョンを指定することで、ユーザはディスク上の既存の全てのメッセージが指定のバージョン以下であることを保証します。この値を間違って設定すると、古いバージョンのコンシューマが理解できないフォーマットを使ってメッセージを受信するため、それらは壊してしまうでしょう。string0.10.0-IV1medium
log.message.timestamp.difference.max.msブローカーがメッセージを付け取った時のタイムスタンプと、その中で指定されたタイムスタンプとの間で許される最大の差異。message.timestamp.type=CreateTime であれば、タイムスタンプの違いがこの閾値を超えた場合にメッセージは却下されるでしょう。もし message.timestamp.type=LogAppendTime であれば、この設定は無視されます。long9223372036854775807[0,...]medium
log.message.timestamp.typeメッセージ内のタイムスタンプが、メッセージが生成された時間か、ログが追加された時間かどうかを定義します。値は `CreateTime` あるいは `LogAppendTime` のどちらかでなければなりません。stringCreateTime[CreateTime, LogAppendTime]medium
log.preallocate新しいセグメントを作る場合にあらかじめファイルを割り当てるべきか?Windows上でKafkaを使う場合は、たぶんtrueに設定する必要があります。booleanfalsemedium
log.retention.check.interval.msログクリーナーがいずれかのログが削除される対象かどうかをチェックする頻度のミリ秒long300000[1,...]medium
max.connections.per.ip各ipアドレスから接続可能な最大数int2147483647[1,...]medium
max.connections.per.ip.overridesPer-ip or hostname overrides to the default maximum number of connectionsstring""medium
num.partitionsトピック毎のログパーティションのデフォルトの数int1[1,...]medium
principal.builder.classPrincipalBuilder インタフェースを実装するクラスの完全修飾名。これは現在のところSSL SecurityProtocolを使って接続のためのPrincipalを構築するために使われます。クラスclass org.apache.kafka.common.security.auth.DefaultPrincipalBuildermedium
producer.purgatory.purge.interval.requestsThe purge interval (in number of requests) of the producer request purgatoryint1000medium
replica.fetch.backoff.msThe amount of time to sleep when fetch partition error occurs.int1000[0,...]medium
reserved.broker.max.idbroker.idのために使うことができる最大の数int1000[0,...]medium
sasl.enabled.mechanismsKafkaサーバ内で利用可能なSASL機構のリスト。リストにはセキュリティプロバイダが利用可能な任意の機構が含まれるかも知れません。デフォルトではGSSAPIだけが有効です。list[GSSAPI]medium
sasl.kerberos.kinit.cmdKerberos kinit コマンドライン パス。string/usr/bin/kinitmedium
sasl.kerberos.min.time.before.reloginリフレッシュ試行間のログインスレッドのスリープ時間。long60000medium
sasl.kerberos.principal.to.local.rulesプリンシパル名からショート名(一般的にオペレーティングシステムのユーザ名)へのマッピングのルールのリスト。ルールは順番に評価され、プリンシパル名に合致する最初のルールがショート名にマップするために使われます。リスト内の後のどのようなルールも無視されます。デフォルトでは、{username}/{hostname}@{REALM} の形式のプリンシパル名は {username} にマップされます。形式についての詳細は、 セキュリティ認証とaclを見てください。list[DEFAULT]medium
sasl.kerberos.service.nameKafkaが実行するKerbrosプリンシパル名。これはKafkaのJAAS設定あるいはKafkaの設定のどちらかで定義することができます。stringnullmedium
sasl.kerberos.ticket.renew.jitter更新時間に追加されるランダムなジッターのパーセンテージ。double0.05medium
sasl.kerberos.ticket.renew.window.factorLogin thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.double0.8medium
sasl.mechanism.inter.broker.protocol内部ブローカー通信に使われるSASL機構。デフォルトは GSSAPI です。stringGSSAPImedium
security.inter.broker.protocolブローカー間で通信するために使われるセキュリティプロトコル。有効な値は: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL。stringPLAINTEXTmedium
ssl.cipher.suitescipher スイーツのリストこれはTLSあるいはSSLネットワークプロトコルを使うネットワーク接続のためのセキュリティ設定を取り決めるために使われる、認証、暗号化、MACおよびキー交換アルゴリズムの名前の組み合わせです。デフォルトでは全ての利用可能なcipherスイーツがサポートされます。listnullmedium
ssl.client.authクライアント認証をリクエストするためのKafkaブローカーを設定します。以下の設定が一般的です:
  • ssl.client.auth=required If set to required client authentication is required.
  • ssl.client.auth=requested これはクライアント認証が任意であることを意味します。requestedと異なり、もしこのオプションが設定された場合、クライアントは自身について認証情報を提供しない事を選択できます。
  • ssl.client.auth=none これはクライアント認証が必要では無いことを意味します。
stringnone[required, requested, none]medium
ssl.enabled.protocolsSSL接続のために有効にされるプロトコルのリスト。list[TLSv1.2, TLSv1.1, TLSv1]medium
ssl.key.passwordキーストアファイル内の秘密キーのパスワード。これはクライアントについては任意です。passwordnullmedium
ssl.keymanager.algorithmSSL接続のためにキーマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されたキーマネージャーファクトリーアルゴリズムです。stringSunX509medium
ssl.keystore.locationキーストアーファイルの場所。これはクライアントについては任意で、クライアントのための相互認証のために使うことができます。stringnullmedium
ssl.keystore.passwordキーストアーファイルのためのストアパスワード。これはクライアントについては任意で、ssl.keystore.locationが設定された場合のみ必要です。 passwordnullmedium
ssl.keystore.typeキーストアファイルのファイル形式。これはクライアントについては任意です。stringJKSmedium
ssl.protocolSSLContextを生成するために使われるSSLプロトコル。デフォルトの設定はTLSで、これはほとんどの場合において問題ありません。最近のJVMで許可される値は、 TLS, TLSv1.1 および TLSv1.2 です。SSL, SSLv2 と SSLv3 は古いJVMではサポートされるかも知れませんが、これらの使用は既知のセキュリティ脆弱性のため推奨されません。stringTLSmedium
ssl.providerSSL接続のために使われるセキュリティプロバイダの名前。デフォルト値はJVMのデフォルトのセキュリティプロバイダです。stringnullmedium
ssl.trustmanager.algorithmSSL接続のためにトラストマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されトラストーマネージャーファクトリーアルゴリズムです。stringPKIXmedium
ssl.truststore.locationトラストストアーファイルの場所。 stringnullmedium
ssl.truststore.passwordトラストストアーファイルのパスワード。 passwordnullmedium
ssl.truststore.typeトラストストアファイルのファイル形式。stringJKSmedium
authorizer.class.name認証のために使われるべき認証クラスstring""low
metric.reportersメトリクス レポーターとして使われるクラスのリスト。MetricReporter インタフェースの実装により、新しいメトリックの生成を知らせるクラスをプラグインすることができます。JMX統計を登録するために常に JmxReporter が含まれます。list[]low
metrics.num.samplesメトリクスを計算するために保持される標本の数。int2[1,...]low
metrics.sample.window.msメトリクスの標本が計算されるための時間の窓。long30000[1,...]low
quota.window.numメモリ内に保持する標本の数int11[1,...]low
quota.window.size.seconds各標本の時間の間隔int1[1,...]low
ssl.endpoint.identification.algorithmサーバの証明書を使ってサーバのホスト名を検証するためのエンドポイント識別アルゴリズム。 stringnulllow
zookeeper.sync.time.msZKリーダーからどれだけZKフォロワーが遅れることができるかint2000low

ブローカー設定についての詳細はscalaクラスkafka.server.KafkaConfigの中で見つけることができます。

Topic-level configuration Configurations pertinent to topics have both a global default as well an optional per-topic override. トピック毎の設定が与えられない場合は、グローバルのデフォルトが使われます。この上書きはトピックの作成時に1つ以上の--config オプションを与えることで設定することができます。この例は独自の最大メッセージサイズとフラッシュレートを持つmy-topicという名前のトピックを生成します:
 > bin/kafka-topics.sh --zookeeper localhost:2181 --create --topic my-topic --partitions 1
        --replication-factor 1 --config max.message.bytes=64000 --config flush.messages=1
上書きは、他のトピックコマンドを使って変更あるいは後で設定することもできます。この例は my-topicのための最大メッセージサイズを更新します:
 > bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic my-topic
    --config max.message.bytes=128000
上書きを削除するために、以下のようにすることができます
 > bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic my-topic
    --delete-config max.message.bytes
以下はトピックレベルの設定です。このプロパティのためのサーバのデフォルトの設定は Server Default Property の頭書きのもとで与えられ、サーバの設定の中でこのデフォルトを設定することで上書きを指定されていないトピックに渡されるデフォルトを変更することができます。
属性 デフォルト Server Default Property 解説
cleanup.policy delete log.cleanup.policy "delete" または "compact" のどちらかの文字列。この文字列は古いログセグメント上で使用する保持ポリシーを指定します。デフォルトのポリシー ("delete") は保持期間あるいはサイズの制限に到達した時に古いセグメントを破棄するでしょう。"compact" 設定はトピックでのlog のコンパクション を有効にするでしょう。
delete.retention.ms 86400000 (24 時間) log.cleaner.delete.retention.ms The amount of time to retain delete tombstone markers for log compacted topics. This setting also gives a bound on the time in which a consumer must complete a read if they begin from offset 0 to ensure that they get a valid snapshot of the final stage (otherwise delete tombstones may be collected before they complete their scan).
flush.messages None log.flush.interval.messages この設定はログに書かれるデータのfsyncを強制する間隔を指定することができます。例えば、もしこれが1に設定された場合、各メッセージの後にfsyncされるでしょう; もし5であれば各5メッセージ毎にfsyncするでしょう。一般的には、これを使わずに、耐久性のためにリプリケーションを使い、オペレーティングシステムのバックグラウンドフラッシュ機能のほうがもっと効率的なためそれにさせることをお勧めします。この設定はトピック毎ベースで上書きすることができます(トピック毎の設定の章を見てください)。
flush.ms None log.flush.interval.ms この設定はログに書かれるデータのfsyncを強制する時間を指定することができます。例えば、これが1000に設定された場合、1000ms過ぎた後でfsyncするでしょう。一般的には、これを使わずに、耐久性のためにリプリケーションを使い、オペレーティングシステムのバックグラウンドフラッシュ機能のほうがもっと効率的なためそれにさせることをお勧めします。
index.interval.bytes 4096 log.index.interval.bytes この設定はKafkaがオフセットインデックスにエントリを追加する頻度を制御します。デフォルトの設定はおおよそ各4096バイトごとにメッセージをインデックスすることを保証します。もっとインデックスを増やすことでログの正確な場所の近くに読み込みをジャンプすることができますが、インデックスが大きくなります。おそらくこれを変更する必要はないでしょう。
max.message.bytes 1,000,000 message.max.bytes これはKafkaがこのトピックに追加することができる最大のメッセージサイズです。このサイズを増加する場合は、この大きさまでメッセージを読み込むことができるようにコンピュータの読み込みサイズを増加する必要もあることに注意してください。
min.cleanable.dirty.ratio 0.5 log.cleaner.min.cleanable.ratio この設定はログの圧縮機がログを掃除しようとする頻度を制御します(log compaction が有効であると仮定)。デフォルトでは、ログの50%以上がコンパクト化された場所にあるログを掃除することを避けるでしょう。この率はデュープリケートによってログ内で消費される領域の最大を制限します(50%ではログの最大50%がデュープリケートされるかも知れません)。率を高くすることは、より少なく、より効率的な掃除を意味しますが、ログ内のより多くの消費される領域を意味するでしょう。
min.insync.replicas 1 min.insync.replicas When a producer sets acks to "all", min.insync.replicas specifies the minimum number of replicas that must acknowledge a write for the write to be considered successful. If this minimum cannot be met, then the producer will raise an exception (either NotEnoughReplicas or NotEnoughReplicasAfterAppend). 一緒に使った場合、min.insync.replicas と acks は素晴らしい耐久性の保証を強化することができます。A typical scenario would be to create a topic with a replication factor of 3, set min.insync.replicas to 2, and produce with acks of "all". これは、もしレプリカの過半数が書き込みを受け取らなかった場合にプロデューサが例外を上げることを保証するでしょう。
retention.bytes None log.retention.bytes This configuration controls the maximum size a log can grow to before we will discard old log segments to free up space if we are using the "delete" retention policy. デフォルトでは時間の制限だけでサイズの制限はありません。
retention.ms 7 days log.retention.minutes This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. これはコンシューマがデータをどれだけ早く読まなければならないかのSLAを表します。
segment.bytes 1 GB log.segment.bytes この設定はログのためのセグメントファイルサイズを制御します。Retention and cleaning is always done a file at a time so a larger segment size means fewer files but less granular control over retention.
segment.index.bytes 10 MB log.index.size.max.bytes この設定はオフセットをファイルの場所にマップするインデックスのサイズを制御します。このインデックスファイルはあらかじめ割り当てられていて、ログがロールした後でのみ縮小されます。通常この設定を変更する必要はありません。
segment.ms 7 days log.roll.hours This configuration controls the period of time after which Kafka will force the log to roll even if the segment file isn't full to ensure that retention can delete or compact old data.
segment.jitter.ms 0 log.roll.jitter.{ms,hours} logRollTimeMillis から差し引く最大のジッター。

3.2プロデューサの設定

以下はJavaプロデューサの設定です:
名前 解説 種類 デフォルト 有効な値 重要性
bootstrap.serversKafkaクラスタへの初期の接続を確立するために使うホスト/ポートのペアのリスト。クライアントはブートストラッピングのためにここでどのサーバが指定されたかに関わらず全てのサーバを利用するでしょう — このリストはサーバの完全なセットを見つけるために使われる初期のホストにのみ影響を与えます。このリストはhost1:port1,host2:port2,...の形式でなければなりません。これらのサーバは完全なクラスタの会員(動的に変わるかも知れません)を見つけるための初期接続に使われるため、このリストはサーバの完全なセットを含む必要はありません (しかし、サーバがダウンした場合のために1つ以上が望まれるかも知れません)。listhigh
key.serializerSerializer インタフェースを実装するキーのためのシリアライザ クラス。クラスhigh
value.serializerSerializer インタフェースを実装する値のためのシリアライザ クラス。クラスhigh
acksThe number of acknowledgments the producer requires the leader to have received before considering a request complete. これは送信されたレコードの持続性を制御します。以下の設定が一般的です:
  • acks=0 0に設定されるとプロデューサはサーバからの承認を全く待たないでしょう。レコードはすぐにソケットバッファに追加され、送信されたものと見なされます。この場合サーバがレコードを受け取ったかどうかの保証はできません。そしてretries 設定は効果が無いでしょう (クライアントは一般的に障害を知らないため)。各レコードについて返されるオフセットは常に -1 に設定されるでしょう。
  • acks=1 これは、リーダーはレコードをローカルログに書き込むが、すべてのフォロワーからの完全な応答を待たずに応答するでしょう。In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost.
  • acks=all これは、リーダーはレコードに応答するためにin-syncレプリカの完全なセットを待つだろうことを意味します。これは、少なくとも1つのin-syncレプリカが生きている限りレコードは失われないだろうことを保証します。これはもっとも強力な利用可能な保証です。
string1[all, -1, 0, 1]high
buffer.memoryプロデューサがサーバに送られるのを待っているレコードをバッファするために使うことができるメモリの総バイト数。If records are sent faster than they can be delivered to the server the producer will block for max.block.ms after which it will throw an exception.

この設定は大まかにプロデューサが利用しようとする総メモリに対応しますが、プロデューサが使用する全てのメモリがバッファリングに使われるわけではないためハードバウンドではありません。いくつかの追加のメモリが圧縮(圧縮が有効な場合)と、やってきているリクエストを保持するために使われるでしょう。

long33554432[0,...]high
compression.typeプロデューサによって生成された全てのデータのための圧縮タイプ。デフォルトは none (つまり、非圧縮)。有効な値は、none, gzip, snappy あるいは lz4 です。Compression is of full batches of data, so the efficacy of batching will also impact the compression ratio (more batching means better compression).stringnonehigh
retriesSetting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first.int0[0,...,2147483647]high
ssl.key.passwordキーストアファイル内の秘密キーのパスワード。これはクライアントについては任意です。passwordnullhigh
ssl.keystore.locationキーストアーファイルの場所。これはクライアントについては任意で、クライアントのための相互認証のために使うことができます。stringnullhigh
ssl.keystore.passwordキーストアーファイルのためのストアパスワード。これはクライアントについては任意で、ssl.keystore.locationが設定された場合のみ必要です。 passwordnullhigh
ssl.truststore.locationトラストストアーファイルの場所。 stringnullhigh
ssl.truststore.passwordトラストストアーファイルのパスワード。 passwordnullhigh
batch.sizeThe producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. これはクライアントとサーバの両方でパフォーマンスを助けます。この設定はデフォルトのバッチサイズをバイトで制御します。

No attempt will be made to batch records larger than this size.

Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.

A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records.

int16384[0,...]medium
client.idリクエストする時にサーバに渡されるid文字列。これの目的は、サーバ側のリクエストのログに論理アプリケーション名を追加することで、ip/portを超えたリクエストのソースの追跡をすることです。string""medium
connections.max.idle.msこの設定によって指定されるミリ秒後にアイドルの接続を閉じます。long540000medium
linger.msThe producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. しかし、ある状況では、クライアントは控えめな負荷の場合でもリクエストの数を減らしたいと思うかも知れません。This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. これはTCPでのNagleアルゴリズムへの相似として考えることができます。This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. この設定のデフォルトは 0 です (つまり、遅延はありません)。例えば、linger.ms=5に設定すると、送信されるリクエストの数を減らす効果がありますが、負荷が無い時にレコードの送信に5msのレイテンシを追加するでしょう。long0[0,...]medium
max.block.msThe configuration controls how long KafkaProducer.send() and KafkaProducer.partitionsFor() will block.These methods can be blocked either because the buffer is full or metadata unavailable.Blocking in the user-supplied serializers or partitioner will not be counted against this timeout.long60000[0,...]medium
max.request.sizeリクエストの最大バイトサイズ。これは最大レコードサイズの効果的なキャップでもあります。サーバはこれとは異なるかも知れないレコードサイズ上の独自のキャップを持つことに注意してください。This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests.int1048576[0,...]medium
partitioner.classPartitioner インタフェースを実装するパーティショナークラス。クラスclass org.apache.kafka.clients.producer.internals.DefaultPartitionermedium
receive.buffer.bytesデータを読み込む時に使われるTCPレシーバーバッファ (SO_RCVBUF) のサイズ。int32768[0,...]medium
request.timeout.msこの設定はクライアントがリクエストの応答を待つ総時間の最大を制御します。タイムアウトの時間が経過する前に応答が受信されない場合は、必要であればクライアントはリクエストを再送信するでしょう。あるいは再試行が使い尽くされた場合は失敗するでしょう。int30000[0,...]medium
sasl.kerberos.service.nameKafkaが実行するKerbrosプリンシパル名。これはKafkaのJAAS設定あるいはKafkaの設定のどちらかで定義することができます。stringnullmedium
sasl.mechanismクライアント接続で使われるSASL機構。これはセキュリティプロバイダが利用可能な全ての機構です。GSSAPI がデフォルトの機構です。stringGSSAPImedium
security.protocolブローカーと通信するために使われるプロトコル。有効な値は: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL。stringPLAINTEXTmedium
send.buffer.bytesデータを送信する時に使われるTCP送信バッファ (SO_SNDBUF)のサイズ。int131072[0,...]medium
ssl.enabled.protocolsSSL接続のために有効にされるプロトコルのリスト。list[TLSv1.2, TLSv1.1, TLSv1]medium
ssl.keystore.typeキーストアファイルのファイル形式。これはクライアントについては任意です。stringJKSmedium
ssl.protocolSSLContextを生成するために使われるSSLプロトコル。デフォルトの設定はTLSで、これはほとんどの場合において問題ありません。最近のJVMで許可される値は、 TLS, TLSv1.1 および TLSv1.2 です。SSL, SSLv2 と SSLv3 は古いJVMではサポートされるかも知れませんが、これらの使用は既知のセキュリティ脆弱性のため推奨されません。stringTLSmedium
ssl.providerSSL接続のために使われるセキュリティプロバイダの名前。デフォルト値はJVMのデフォルトのセキュリティプロバイダです。stringnullmedium
ssl.truststore.typeトラストストアファイルのファイル形式。stringJKSmedium
timeout.msThe configuration controls the maximum amount of time the server will wait for acknowledgments from followers to meet the acknowledgment requirements the producer has specified with the acks configuration. タイムアウト時間が経過してリクエストされた通知の数が合致しない場合は、エラーが返されるでしょう。このタイムアウトはサーバ側で測定され、リクエストのネットワークのレイテンシを含みません。int30000[0,...]medium
block.on.buffer.fullメモリバッファが枯渇した場合、新しいレコード(ブロック)の受付を止めるか、エラーを投げる必要があります。デフォルトではこの設定はfalseで、プロデューサはBufferExhaustException を投げないでしょう。 代わりに、TimeoutExceptionを投げる、ブロックにmax.block.ms の値を使うでしょう。このプロパティにtrueを設定すると、max.block.ms に Long.MAX_VALUE を設定するでしょう。また、このプロパティがtrueに設定されると、パラメータmetadata.fetch.timeout.ms はもう受け付けられません。

このパラメータは非推奨で、将来のリリースでは削除されるでしょう。パラメータmax.block.msが代わりに使われるべきです。

booleanfalselow
interceptor.classesインタセプタとして使われるクラスのリスト。ProducerInterceptor インタフェースの実装により、Kafkaクラスタに発行される前にプロデューサによって受け取られるレコードを捉え(そしておそらく変化す)ることができます。デフォルトでは、インタセプタはありません。listnulllow
max.in.flight.requests.per.connectionクライアントがブロックされる前に1つの接続上で送信するだろう、返事の無いリクエストの最大数。この設定が1より大きく設定され、失敗した送信がある場合は、再試行(つまり、再試行が有効な場合)により、メッセージの再注文の可能性があります。int5[1,...]low
metadata.fetch.timeout.msデータがトピックに送信される最初の時に、どのサーバがトピックのパーティションを提供するかを知るためにトピックについてのメタdーたを取得する必要があります。This fetch to succeed before throwing an exception back to the client.long60000[0,...]low
metadata.max.age.msThe period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.long300000[0,...]low
metric.reportersメトリクス レポーターとして使われるクラスのリスト。MetricReporter インタフェースの実装により、新しいメトリックの生成を知らせるクラスをプラグインすることができます。JMX統計を登録するために常に JmxReporter が含まれます。list[]low
metrics.num.samplesメトリクスを計算するために保持される標本の数。int2[1,...]low
metrics.sample.window.msメトリクスの標本が計算されるための時間の窓。long30000[0,...]low
reconnect.backoff.ms指定されたホストに再接続しようとするまで待機する総時間。これにより短いループ内でホストに繰り返し接続することを防ぎます。このbackoffはコンシューマによってブローカーに送信される全てのリクエストに適用されます。long50[0,...]low
retry.backoff.ms指定されたトピックパーティションへの失敗したリクエストを再試行しようとするまで待機する総時間。これにより短いループ内で幾つかの失敗のシナリオがある場合に繰り返しリクエストすることを防ぎます。long100[0,...]low
sasl.kerberos.kinit.cmdKerberos kinit コマンドライン パス。string/usr/bin/kinitlow
sasl.kerberos.min.time.before.reloginリフレッシュ試行間のログインスレッドのスリープ時間。long60000low
sasl.kerberos.ticket.renew.jitter更新時間に追加されるランダムなジッターのパーセンテージ。double0.05low
sasl.kerberos.ticket.renew.window.factorLogin thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.double0.8low
ssl.cipher.suitescipher スイーツのリストこれはTLSあるいはSSLネットワークプロトコルを使うネットワーク接続のためのセキュリティ設定を取り決めるために使われる、認証、暗号化、MACおよびキー交換アルゴリズムの名前の組み合わせです。デフォルトでは全ての利用可能なcipherスイーツがサポートされます。listnulllow
ssl.endpoint.identification.algorithmサーバの証明書を使ってサーバのホスト名を検証するためのエンドポイント識別アルゴリズム。 stringnulllow
ssl.keymanager.algorithmSSL接続のためにキーマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されたキーマネージャーファクトリーアルゴリズムです。stringSunX509low
ssl.trustmanager.algorithmSSL接続のためにトラストマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されトラストーマネージャーファクトリーアルゴリズムです。stringPKIXlow

従来のScala プロデューサの設定に興味がある人のために、ここで情報を見つけることができます。

3.3コンシューマの設定

古い0.8コンシューマの設定と新しいコンシューマの設定の両方をそれぞれ以下で紹介します。

3.3.1古いコンシューマの設定

古いコンシューマの設定の本質的な要素は以下の通りです:
属性 デフォルト 解説
group.id このコンシューマに所属するコンシューマの処理のグループをユニークに識別する文字列。複数のプロセスに同じグループidを設定することは、それらが全て同じコンシューマグループの一部分であることを示します。
zookeeper.connect hostname:port の形式でZookeeperの接続文字列を指定します。ここでhostとportはZooKeeperサーバのホストとポートです。Zookeeperのマシーンがダウンしている時に他のZooKeeperノードを経由して接続できるようにするために、hostname1:port1,hostname2:port2,hostname3:port3の形式で複数のホストを指定することもできます。

The server may also have a ZooKeeper chroot path as part of it's ZooKeeper connection string which puts its data under some path in the global ZooKeeper namespace. もしそうであればコンシューマは接続文字列の中で同じchrootパスを使う必要があります。例えば、/chroot/path のchrootパスを指定するために、hostname1:port1,hostname2:port2,hostname3:port3/chroot/pathとして接続文字列を指定するでしょう。

consumer.id null

設定されていない場合は自動的に生成されます。

socket.timeout.ms 30 * 1000 ネットワークリクエストのためのソケットタイムアウト。実際のタイムアウトの設定は max.fetch.wait + socket.timeout.ms でしょう。
socket.receive.buffer.bytes 64 * 1024 ネットワークリクエストのためのソケット受信バッファ
fetch.message.max.bytes 1024 * 1024 各フェッチリクエストの中で各トピックパーティションについてフェッチしようとするメッセージのバイト数。これらのバイトは各パーティションについてメモリの中に読み込まれるでしょう。つまり、コンシューマによって使われるメモリを制御するのに役立ちます。The fetch request size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch.
num.consumer.fetchers 1 データをフェッチするのに使われるfetcherスレッドの数。
auto.commit.enable true trueの場合、コンシューマによって既にフェッチされたメッセージのオフセットが定期的にZooKeeperにコミットされます。このコミットされたオフセットはプロセスが失敗した時に新しいコンシューマが開始するだろう場所として使われるでしょう。
auto.commit.interval.ms 60 * 1000 コンシューマのオフセットがzooKeeperにコミットされた頻度のms。
queued.max.message.chunks 2 消費のためにバッファされるメッセージチャンクの最大数。各チャンクは fetch.message.max.bytes まで大きくなります。
rebalance.max.retries 4 When a new consumer joins a consumer group the set of consumers attempt to "rebalance" the load to assign partitions to each consumer. この割り当てが開始されている間にコンシューマの設定が変更されると、再バランスは失敗し再試行するでしょう。この設定は諦めるまでの最大の試行数を制御します。
fetch.min.bytes 1 サーバが各フェッチリクエストについて返さなければならないデータの最小量。十分なデータが利用可能では無い場合、リクエストはリクエストに返答する前に多くのデータを集めるのを待つでしょう。
fetch.wait.max.ms 100 すぐにfetch.min.bytes を満たす十分なデータが無い場合に、サーバがフェッチリクエストに応答する前にブロックする最大の時間。
rebalance.backoff.ms 2000 再バランス時の再試行の間のバックオフ時間。明示的に設定されない場合、zookeeper.sync.time.ms の値が使われます。
refresh.leader.backoff.ms 200 パーティションのリーダが行方不明になった時にリーダを決める前に待つバックオフ時間。
auto.offset.reset largest

ZooKeeperに初期オフセットが無いか、オフセットが範囲外の場合に、何をするか:
* smallest : 自動的にオフセットを最小のオフセットに再設定します
* largest : 自動的にオフセットを最大のオフセットに再設定します
* それ以外: コンシューマに例外を投げます

consumer.timeout.ms -1 指定された間隔の後で消費できるメッセージが無い場合は、コンシューマにタイムアウトの例外を投げます
exclude.internal.topics true (オフセットのような)内部トピックからのメッセージをコンシューマに公開すべきかどうか。
client.id group id value クライアントidは呼び出しの追跡を手助けするために各リクエストの中で送信されるユーザ定義の文字列です。それはリクエストを生成するアプリケーションを論理的に識別しなければなりません。
zookeeper.session.timeout.ms  6000 ZooKeeper セッション タイムアウト。もしコンシューマがZooKeeperへのハートビットに失敗した場合、この期間の間deadであると見なされ、再バランスが起こるでしょう。
zookeeper.connection.timeout.ms 6000 クライアントがzookeeperへの接続を確立する間待つ最大時間。
zookeeper.sync.time.ms  2000 ZKリーダーからどれだけZKフォロワーが遅れることができるか
offsets.storage zookeeper どこにオフセットが格納されるべきかを選択します(zookeeperあるいはkafka)。
offsets.channel.backoff.ms 1000 オフセットチャネルに再接続するか、失敗したオフセットのフェッチ/コミット リクエストを再試行する時のバックオフ期間。
offsets.channel.socket.timeout.ms 10000 オフセットのフェッチ/コミット リクエストのための応答を読み込む時のソケットタイムアウト。このタイムアウトはオフセットマネージャへのクエリに使われるConsumerMetadataリクエストのためにも使われます。
offsets.commit.max.retries 5 障害時にこの回数までオフセットのコミットを再試行します。この再試行のカウントはシャットダウン時のオフセットコミットにのみ適用されます。自動コミットスレッドから生成されたコミットへは適用されません。またコミットオフセットの前のオフセット調整のためのクエリの試行へは適用されません。つまり、コンシューマのメタデータ リクエストが何らかの理由で失敗した場合、再試行され、その再試行はこの制限に対してカウントされないでしょう。
dual.commit.enabled true offsets.storageとして"kafka"を使っている場合は、二つのコミットオフセットを(Kafkaに加えて)ZooKeeperにコミットすることができます。これは、zookeeperに基づいたオフセットストレージからkafkaに基づいたオフセットストレージに移設する時に必要になります。指定されたコンシューマグループについては、(ZooKeeperへ直接の代わりに)グループ内の全てのインスタンスがブローカーにオフセットをコミットする新しいバージョンに移行された後でこれをオフにすると安全です。
partition.assignment.strategy range

パーティションをコンシューマのストリームに割り当てるために、"range" あるいは "roundrobin" 戦略から選びます。

round-robin パーティション アサイナーは全ての利用可能なパーティションと全ての利用可能なコンシューマスレッドを割りつけます。それからパーティションからコンシューマスレッドへの round-robin の割り当てを進めます。a全てのコンシューマのインスタンスの購読が同一の場合、パーティションは均一に分散されるでしょう。(i.e., the partition ownership counts will be within a delta of exactly one across all consumer threads.) Round-robin assignment is permitted only if: (a) Every topic has the same number of streams within a consumer instance (b) The set of subscribed topics is identical for every consumer instance within the group.

範囲のパーティションはトピックベースで動作します。各トピックについて、利用可能なパーティションを数字順に、コンシューマのスレッドを辞書順に配置します。それから、各コンシューマに割り当てるパーティションの数を決定するために、パーティションの数をコンシューマ ストリーム(スレッド)の総数で割ります。均等に分割できない場合、最初の幾つかのコンシューマは1つ余分なパーティションを持つでしょう。

コンシューマの設定に関する詳細は、scala クラス kafka.consumer.ConsumerConfigで見つかるでしょう。

3.3.2新しいコンシューマの設定

0.9.0.0 から、既存の簡単で高レベルのコンシューマの置き換えに努力してきました。コードはベータ品質と見なされます。以下は新しいコンシューマのための設定です:
名前 解説 種類 デフォルト 有効な値 重要性
bootstrap.serversKafkaクラスタへの初期の接続を確立するために使うホスト/ポートのペアのリスト。クライアントはブートストラッピングのためにここでどのサーバが指定されたかに関わらず全てのサーバを利用するでしょう — このリストはサーバの完全なセットを見つけるために使われる初期のホストにのみ影響を与えます。このリストはhost1:port1,host2:port2,...の形式でなければなりません。これらのサーバは完全なクラスタの会員(動的に変わるかも知れません)を見つけるための初期接続に使われるため、このリストはサーバの完全なセットを含む必要はありません (しかし、サーバがダウンした場合のために1つ以上が望まれるかも知れません)。listhigh
key.deserializerDeserializerインタフェースを実装するキーのためのDeserializerクラス。クラスhigh
value.deserializerDeserializer インタフェースを実装する値のためのDeserializerクラス。クラスhigh
fetch.min.bytesサーバが各フェッチリクエストについて返さなければならないデータの最小量。十分なデータが利用可能では無い場合、リクエストはリクエストに返答する前に多くのデータを集めるのを待つでしょう。デフォルトの設定の1バイトは、データの1バイトが利用可能、あるいはデータの到着を待っているフェッチリクエストがタイムアウトするとすぐにフェッチリクエストに応答することを意味します。これを1より大きいものに設定すると、データの大部分をサーバが待つようになり、ある程度の追加のレイテンシを犠牲にして少しだけサーバのスループットを改善するでしょう。int1[0,...]high
group.idこのコンシューマが所属するコンシューマグループを識別するユニークな文字列。このプロパティは、もしコンシューマがsubscribe(topic)を使ってグループの管理機能、あるいはKafkaベースのオフセットの管理戦略を使う場合に必須です。string""high
heartbeat.interval.msKafkaのグループ管理機能を使う時に、コンシューマのコーディネータへのハートビート間に期待する時間。ハートビートはコンシューマのセッションが活動中であることを保証し、新しいコンシューマがグループに参加あるいは離れる時のリバランスを円滑にするために使われます。値はsession.timeout.msより小さくなければなりませんが、一般的にはその値の1/3より大きく設定されなければなりません。通常の再バランスについては、期待する時間を制御するために少し小さく調整されるかも知れません。int3000high
max.partition.fetch.bytesサーバが返すパーティションあたりのデータの最大総量。リクエストのために使われる総メモリの最大は #partitions * max.partition.fetch.bytes になるでしょう。このサイズは少なくともサーバで可能な最大のメッセージサイズでなければなりません。そうでなければ、プロデューサがコンシューマがフェッチできるより大きなメッセージを送信するかも知れません。もしそうなると、コンシューマはあるパーティション上で大きなメッセージをフェッチしようとして詰まるかも知れません。int1048576[0,...]high
session.timeout.msKafkaのグループ管理機能を使う場合に障害を検知するために使われるタイムアウト。セッションのタイムアウトまでにコンシューマのハートビートが受信されなかった場合、ブローカーはコンシューマが故障したとマークをしグループを再バランスします。ハートビートはpoll()が起動された時のみ送信されるため、より長いセッションタイムアウトによりハードの障害までの長い時間を代償にコンシューマグループのプールループ内でのメッセージの処理により長くできます。プールループ内の処理時間を制御する他のオプションについては、max.poll.records も見てください。値はgroup.min.session.timeout.msgroup.max.session.timeout.ms によって設定されるブローカーの設定内で設定される可能な範囲内でなければならないことに注意してください。int30000high
ssl.key.passwordキーストアファイル内の秘密キーのパスワード。これはクライアントについては任意です。passwordnullhigh
ssl.keystore.locationキーストアーファイルの場所。これはクライアントについては任意で、クライアントのための相互認証のために使うことができます。stringnullhigh
ssl.keystore.passwordキーストアーファイルのためのストアパスワード。これはクライアントについては任意で、ssl.keystore.locationが設定された場合のみ必要です。 passwordnullhigh
ssl.truststore.locationトラストストアーファイルの場所。 stringnullhigh
ssl.truststore.passwordトラストストアーファイルのパスワード。 passwordnullhigh
auto.offset.resetKafkaの初期オフセットが無い場合、あるいは現在のオフセットがサーバ上にもうない場合(例えば、データが削除された)に、何をするか?:
  • earliest: 自動的にオフセットを最も早いものに再設定
  • latest: 自動的にオフセットを最も遅いオフセットに再設定
  • none: コンシューマグループについて以前のオフセットが無い場合はコンシューマに例外を投げる
  • いずれでも無い場合: コンシューマに例外を投げます。
stringlatest[latest, earliest, none]medium
connections.max.idle.msこの設定によって指定されるミリ秒後にアイドルの接続を閉じます。long540000medium
enable.auto.committrueの場合、コンシューマのオフセットはバックグラウンドで定期的にコミットされるでしょう。booleantruemedium
exclude.internal.topics(オフセットのような)内部トピックからのレコードをコンシューマに公開すべきかどうか。true に設定すると、内部トピックからレコードを受け取る唯一の方法はそれを購読することです。booleantruemedium
max.poll.recordspoll()への1つの呼び出しで返されるレコードの最大数。int2147483647[1,...]medium
partition.assignment.strategyグループ管理が使われた場合に、コンシューマの間でパーティションの所有を分散するためにクライアントが使用するパーティション分割ストラテジのクラス名list[org.apache.kafka.clients.consumer.RangeAssignor]medium
receive.buffer.bytesデータを読み込む時に使われるTCPレシーバーバッファ (SO_RCVBUF) のサイズ。int65536[0,...]medium
request.timeout.msこの設定はクライアントがリクエストの応答を待つ総時間の最大を制御します。タイムアウトの時間が経過する前に応答が受信されない場合は、必要であればクライアントはリクエストを再送信するでしょう。あるいは再試行が使い尽くされた場合は失敗するでしょう。int40000[0,...]medium
sasl.kerberos.service.nameKafkaが実行するKerbrosプリンシパル名。これはKafkaのJAAS設定あるいはKafkaの設定のどちらかで定義することができます。stringnullmedium
sasl.mechanismクライアント接続で使われるSASL機構。これはセキュリティプロバイダが利用可能な全ての機構です。GSSAPI がデフォルトの機構です。stringGSSAPImedium
security.protocolブローカーと通信するために使われるプロトコル。有効な値は: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL。stringPLAINTEXTmedium
send.buffer.bytesデータを送信する時に使われるTCP送信バッファ (SO_SNDBUF)のサイズ。int131072[0,...]medium
ssl.enabled.protocolsSSL接続のために有効にされるプロトコルのリスト。list[TLSv1.2, TLSv1.1, TLSv1]medium
ssl.keystore.typeキーストアファイルのファイル形式。これはクライアントについては任意です。stringJKSmedium
ssl.protocolSSLContextを生成するために使われるSSLプロトコル。デフォルトの設定はTLSで、これはほとんどの場合において問題ありません。最近のJVMで許可される値は、 TLS, TLSv1.1 および TLSv1.2 です。SSL, SSLv2 と SSLv3 は古いJVMではサポートされるかも知れませんが、これらの使用は既知のセキュリティ脆弱性のため推奨されません。stringTLSmedium
ssl.providerSSL接続のために使われるセキュリティプロバイダの名前。デフォルト値はJVMのデフォルトのセキュリティプロバイダです。stringnullmedium
ssl.truststore.typeトラストストアファイルのファイル形式。stringJKSmedium
auto.commit.interval.msもしenable.auto.committrue に設定されている場合に、コンシューマのオフセットがKafkaに自動コミットされる頻度のミリ秒。long5000[0,...]low
check.crcs消費されるレコードのCRC32を自動的にチェックする。これにより、通信上あるいはディスク上でメッセージの改竄が無いことを保証します。この調査はいくらかの負荷があるため、極度にパフォーマンスを求めている場合は無効にされているかも知れません。booleantruelow
client.idリクエストする時にサーバに渡されるid文字列。これの目的は、サーバ側のリクエストのログに論理アプリケーション名を追加することで、ip/portを超えたリクエストのソースの追跡をすることです。string""low
fetch.max.wait.msThe maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch.min.bytes.int500[0,...]low
interceptor.classesインタセプタとして使われるクラスのリスト。Implementing the ConsumerInterceptor interface allows you to intercept (and possibly mutate) records received by the consumer. デフォルトでは、インタセプタはありません。listnulllow
metadata.max.age.msThe period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.long300000[0,...]low
metric.reportersメトリクス レポーターとして使われるクラスのリスト。MetricReporter インタフェースの実装により、新しいメトリックの生成を知らせるクラスをプラグインすることができます。JMX統計を登録するために常に JmxReporter が含まれます。list[]low
metrics.num.samplesメトリクスを計算するために保持される標本の数。int2[1,...]low
metrics.sample.window.msメトリクスの標本が計算されるための時間の窓。long30000[0,...]low
reconnect.backoff.ms指定されたホストに再接続しようとするまで待機する総時間。これにより短いループ内でホストに繰り返し接続することを防ぎます。このbackoffはコンシューマによってブローカーに送信される全てのリクエストに適用されます。long50[0,...]low
retry.backoff.ms指定されたトピックパーティションへの失敗したリクエストを再試行しようとするまで待機する総時間。これにより短いループ内で幾つかの失敗のシナリオがある場合に繰り返しリクエストすることを防ぎます。long100[0,...]low
sasl.kerberos.kinit.cmdKerberos kinit コマンドライン パス。string/usr/bin/kinitlow
sasl.kerberos.min.time.before.reloginリフレッシュ試行間のログインスレッドのスリープ時間。long60000low
sasl.kerberos.ticket.renew.jitter更新時間に追加されるランダムなジッターのパーセンテージ。double0.05low
sasl.kerberos.ticket.renew.window.factorLogin thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.double0.8low
ssl.cipher.suitescipher スイーツのリストこれはTLSあるいはSSLネットワークプロトコルを使うネットワーク接続のためのセキュリティ設定を取り決めるために使われる、認証、暗号化、MACおよびキー交換アルゴリズムの名前の組み合わせです。デフォルトでは全ての利用可能なcipherスイーツがサポートされます。listnulllow
ssl.endpoint.identification.algorithmサーバの証明書を使ってサーバのホスト名を検証するためのエンドポイント識別アルゴリズム。 stringnulllow
ssl.keymanager.algorithmSSL接続のためにキーマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されたキーマネージャーファクトリーアルゴリズムです。stringSunX509low
ssl.trustmanager.algorithmSSL接続のためにトラストマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されトラストーマネージャーファクトリーアルゴリズムです。stringPKIXlow

3.4Kafka 接続設定

Below is the configuration of the Kafka Connect framework.
名前 解説 種類 デフォルト 有効な値 重要性
config.storage.topickafka topic to store configsstringhigh
group.idA unique string that identifies the Connect cluster group this worker belongs to.stringhigh
internal.key.converterConverter class for internal key Connect data that implements the Converter interface. Used for converting data like offsets and configs.クラスhigh
internal.value.converterConverter class for offset value Connect data that implements the Converter interface. Used for converting data like offsets and configs.クラスhigh
key.converterConverter class for key Connect data that implements the Converter interface.クラスhigh
offset.storage.topickafka topic to store connector offsets instringhigh
status.storage.topickafka topic to track connector and task statusstringhigh
value.converterConverter class for value Connect data that implements the Converter interface.クラスhigh
bootstrap.serversKafkaクラスタへの初期の接続を確立するために使うホスト/ポートのペアのリスト。クライアントはブートストラッピングのためにここでどのサーバが指定されたかに関わらず全てのサーバを利用するでしょう — このリストはサーバの完全なセットを見つけるために使われる初期のホストにのみ影響を与えます。このリストはhost1:port1,host2:port2,...の形式でなければなりません。これらのサーバは完全なクラスタの会員(動的に変わるかも知れません)を見つけるための初期接続に使われるため、このリストはサーバの完全なセットを含む必要はありません (しかし、サーバがダウンした場合のために1つ以上が望まれるかも知れません)。list[localhost:9092]high
clusterID for this cluster, which is used to provide a namespace so multiple Kafka Connect clusters or instances may co-exist while sharing a single Kafka cluster.stringconnecthigh
heartbeat.interval.msThe expected time between heartbeats to the group coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the worker's session stays active and to facilitate rebalancing when new members join or leave the group. 値はsession.timeout.msより小さくなければなりませんが、一般的にはその値の1/3より大きく設定されなければなりません。通常の再バランスについては、期待する時間を制御するために少し小さく調整されるかも知れません。int3000high
session.timeout.msKafkaのグループ管理機能を使う場合に障害を検知するために使われるタイムアウト。int30000high
ssl.key.passwordキーストアファイル内の秘密キーのパスワード。これはクライアントについては任意です。passwordnullhigh
ssl.keystore.locationキーストアーファイルの場所。これはクライアントについては任意で、クライアントのための相互認証のために使うことができます。stringnullhigh
ssl.keystore.passwordキーストアーファイルのためのストアパスワード。これはクライアントについては任意で、ssl.keystore.locationが設定された場合のみ必要です。 passwordnullhigh
ssl.truststore.locationトラストストアーファイルの場所。 stringnullhigh
ssl.truststore.passwordトラストストアーファイルのパスワード。 passwordnullhigh
connections.max.idle.msこの設定によって指定されるミリ秒後にアイドルの接続を閉じます。long540000medium
receive.buffer.bytesデータを読み込む時に使われるTCPレシーバーバッファ (SO_RCVBUF) のサイズ。int32768[0,...]medium
request.timeout.msこの設定はクライアントがリクエストの応答を待つ総時間の最大を制御します。タイムアウトの時間が経過する前に応答が受信されない場合は、必要であればクライアントはリクエストを再送信するでしょう。あるいは再試行が使い尽くされた場合は失敗するでしょう。int40000[0,...]medium
sasl.kerberos.service.nameKafkaが実行するKerbrosプリンシパル名。これはKafkaのJAAS設定あるいはKafkaの設定のどちらかで定義することができます。stringnullmedium
sasl.mechanismクライアント接続で使われるSASL機構。これはセキュリティプロバイダが利用可能な全ての機構です。GSSAPI がデフォルトの機構です。stringGSSAPImedium
security.protocolブローカーと通信するために使われるプロトコル。有効な値は: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL。stringPLAINTEXTmedium
send.buffer.bytesデータを送信する時に使われるTCP送信バッファ (SO_SNDBUF)のサイズ。int131072[0,...]medium
ssl.enabled.protocolsSSL接続のために有効にされるプロトコルのリスト。list[TLSv1.2, TLSv1.1, TLSv1]medium
ssl.keystore.typeキーストアファイルのファイル形式。これはクライアントについては任意です。stringJKSmedium
ssl.protocolSSLContextを生成するために使われるSSLプロトコル。デフォルトの設定はTLSで、これはほとんどの場合において問題ありません。最近のJVMで許可される値は、 TLS, TLSv1.1 および TLSv1.2 です。SSL, SSLv2 と SSLv3 は古いJVMではサポートされるかも知れませんが、これらの使用は既知のセキュリティ脆弱性のため推奨されません。stringTLSmedium
ssl.providerSSL接続のために使われるセキュリティプロバイダの名前。デフォルト値はJVMのデフォルトのセキュリティプロバイダです。stringnullmedium
ssl.truststore.typeトラストストアファイルのファイル形式。stringJKSmedium
worker.sync.timeout.msWhen the worker is out of sync with other workers and needs to resynchronize configurations, wait up to this amount of time before giving up, leaving the group, and waiting a backoff period before rejoining.int3000medium
worker.unsync.backoff.msWhen the worker is out of sync with other workers and fails to catch up within worker.sync.timeout.ms, leave the Connect cluster for this long before rejoining.int300000medium
access.control.allow.methodsSets the methods supported for cross origin requests by setting the Access-Control-Allow-Methods header. The default value of the Access-Control-Allow-Methods header allows cross origin requests for GET, POST and HEAD.string""low
access.control.allow.originValue to set the Access-Control-Allow-Origin header to for REST API requests.To enable cross origin access, set this to the domain of the application that should be permitted to access the API, or '*' to allow access from any domain. The default value only allows access from the domain of the REST API.string""low
client.idリクエストする時にサーバに渡されるid文字列。これの目的は、サーバ側のリクエストのログに論理アプリケーション名を追加することで、ip/portを超えたリクエストのソースの追跡をすることです。string""low
metadata.max.age.msThe period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.long300000[0,...]low
metric.reportersメトリクス レポーターとして使われるクラスのリスト。MetricReporter インタフェースの実装により、新しいメトリックの生成を知らせるクラスをプラグインすることができます。JMX統計を登録するために常に JmxReporter が含まれます。list[]low
metrics.num.samplesメトリクスを計算するために保持される標本の数。int2[1,...]low
metrics.sample.window.msメトリクスの標本が計算されるための時間の窓。long30000[0,...]low
offset.flush.interval.msInterval at which to try committing offsets for tasks.long60000low
offset.flush.timeout.msMaximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt.long5000low
reconnect.backoff.ms指定されたホストに再接続しようとするまで待機する総時間。これにより短いループ内でホストに繰り返し接続することを防ぎます。このbackoffはコンシューマによってブローカーに送信される全てのリクエストに適用されます。long50[0,...]low
rest.advertised.host.nameIf this is set, this is the hostname that will be given out to other workers to connect to.stringnulllow
rest.advertised.portIf this is set, this is the port that will be given out to other workers to connect to.intnulllow
rest.host.nameHostname for the REST API. If this is set, it will only bind to this interface.stringnulllow
rest.portPort for the REST API to listen on.int8083low
retry.backoff.ms指定されたトピックパーティションへの失敗したリクエストを再試行しようとするまで待機する総時間。これにより短いループ内で幾つかの失敗のシナリオがある場合に繰り返しリクエストすることを防ぎます。long100[0,...]low
sasl.kerberos.kinit.cmdKerberos kinit コマンドライン パス。string/usr/bin/kinitlow
sasl.kerberos.min.time.before.reloginリフレッシュ試行間のログインスレッドのスリープ時間。long60000low
sasl.kerberos.ticket.renew.jitter更新時間に追加されるランダムなジッターのパーセンテージ。double0.05low
sasl.kerberos.ticket.renew.window.factorLogin thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.double0.8low
ssl.cipher.suitescipher スイーツのリストこれはTLSあるいはSSLネットワークプロトコルを使うネットワーク接続のためのセキュリティ設定を取り決めるために使われる、認証、暗号化、MACおよびキー交換アルゴリズムの名前の組み合わせです。デフォルトでは全ての利用可能なcipherスイーツがサポートされます。listnulllow
ssl.endpoint.identification.algorithmサーバの証明書を使ってサーバのホスト名を検証するためのエンドポイント識別アルゴリズム。 stringnulllow
ssl.keymanager.algorithmSSL接続のためにキーマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されたキーマネージャーファクトリーアルゴリズムです。stringSunX509low
ssl.trustmanager.algorithmSSL接続のためにトラストマネージャーファクトリーによって使われるアルゴリズム。デフォルト値はJava仮想マシーンのために設定されトラストーマネージャーファクトリーアルゴリズムです。stringPKIXlow
task.shutdown.graceful.timeout.msAmount of time to wait for tasks to shutdown gracefully. This is the total amount of time, not per task. All task have shutdown triggered, then they are waited on sequentially.long5000low

3.5Kafka ストリーム設定

Below is the configuration of the Kafka Streams client library.
名前 解説 種類 デフォルト 有効な値 重要性
application.idAn identifier for the stream processing application. Must be unique within the Kafka cluster. It is used as 1) the default client-id prefix, 2) the group-id for membership management, 3) the changelog topic prefix.stringhigh
bootstrap.serversKafkaクラスタへの初期の接続を確立するために使うホスト/ポートのペアのリスト。クライアントはブートストラッピングのためにここでどのサーバが指定されたかに関わらず全てのサーバを利用するでしょう — このリストはサーバの完全なセットを見つけるために使われる初期のホストにのみ影響を与えます。このリストはhost1:port1,host2:port2,...の形式でなければなりません。これらのサーバは完全なクラスタの会員(動的に変わるかも知れません)を見つけるための初期接続に使われるため、このリストはサーバの完全なセットを含む必要はありません (しかし、サーバがダウンした場合のために1つ以上が望まれるかも知れません)。listhigh
client.idリクエストする時にサーバに渡されるid文字列。これの目的は、サーバ側のリクエストのログに論理アプリケーション名を追加することで、ip/portを超えたリクエストのソースの追跡をすることです。string""high
zookeeper.connectZookeeper connect string for Kafka topics management.string""high
key.serdeSerializer / deserializer class for key that implements the Serde interface.クラスclass org.apache.kafka.common.serialization.Serdes$ByteArraySerdemedium
partition.grouperPartition grouper class that implements the PartitionGrouper interface.クラスclass org.apache.kafka.streams.processor.DefaultPartitionGroupermedium
replication.factorThe replication factor for change log topics and repartition topics created by the stream processing application.int1medium
state.dirDirectory location for state store.string/tmp/kafka-streamsmedium
timestamp.extractorTimestamp extractor class that implements the TimestampExtractor interface.クラスclass org.apache.kafka.streams.processor.ConsumerRecordTimestampExtractormedium
value.serdeSerializer / deserializer class for value that implements the Serde interface.クラスclass org.apache.kafka.common.serialization.Serdes$ByteArraySerdemedium
buffered.records.per.partitionThe maximum number of records to buffer per partition.int1000low
commit.interval.msThe frequency with which to save the position of the processor.long30000low
metric.reportersメトリクス レポーターとして使われるクラスのリスト。MetricReporter インタフェースの実装により、新しいメトリックの生成を知らせるクラスをプラグインすることができます。JMX統計を登録するために常に JmxReporter が含まれます。list[]low
metrics.num.samplesメトリクスを計算するために保持される標本の数。int2[1,...]low
metrics.sample.window.msメトリクスの標本が計算されるための時間の窓。long30000[0,...]low
num.standby.replicasThe number of standby replicas for each task.int0low
num.stream.threadsThe number of threads to execute stream processing.int1low
poll.msThe amount of time in milliseconds to block waiting for input.long100low
state.cleanup.delay.msThe amount of time in milliseconds to wait before deleting state when a partition has migrated.long60000low

4. 設計

4.1モティベーション

We designed Kafka to be able to act as a unified platform for handling all the real-time data feeds a large company might have. To do this we had to think through a fairly broad set of use cases.

It would have to have high-throughput to support high volume event streams such as real-time log aggregation.

It would need to deal gracefully with large data backlogs to be able to support periodic data loads from offline systems.

It also meant the system would have to handle low-latency delivery to handle more traditional messaging use-cases.

We wanted to support partitioned, distributed, real-time processing of these feeds to create new, derived feeds. This motivated our partitioning and consumer model.

Finally in cases where the stream is fed into other data systems for serving, we knew the system would have to be able to guarantee fault-tolerance in the presence of machine failures.

Supporting these uses led us to a design with a number of unique elements, more akin to a database log than a traditional messaging system. We will outline some elements of the design in the following sections.

4.2一貫性

Don't fear the filesystem!

Kafka relies heavily on the filesystem for storing and caching messages. There is a general perception that "disks are slow" which makes people skeptical that a persistent structure can offer competitive performance. In fact disks are both much slower and much faster than people expect depending on how they are used; and a properly designed disk structure can often be as fast as the network.

The key fact about disk performance is that the throughput of hard drives has been diverging from the latency of a disk seek for the last decade. As a result the performance of linear writes on a JBOD configuration with six 7200rpm SATA RAID-5 array is about 600MB/sec but the performance of random writes is only about 100k/sec—a difference of over 6000X. These linear reads and writes are the most predictable of all usage patterns, and are heavily optimized by the operating system. A modern operating system provides read-ahead and write-behind techniques that prefetch data in large block multiples and group smaller logical writes into large physical writes. A further discussion of this issue can be found in this ACM Queue article; they actually find that sequential disk access can in some cases be faster than random memory access!

To compensate for this performance divergence, modern operating systems have become increasingly aggressive in their use of main memory for disk caching. A modern OS will happily divert all free memory to disk caching with little performance penalty when the memory is reclaimed. All disk reads and writes will go through this unified cache. This feature cannot easily be turned off without using direct I/O, so even if a process maintains an in-process cache of the data, this data will likely be duplicated in OS pagecache, effectively storing everything twice.

Furthermore we are building on top of the JVM, and anyone who has spent any time with Java memory usage knows two things:

  1. The memory overhead of objects is very high, often doubling the size of the data stored (or worse).
  2. Java garbage collection becomes increasingly fiddly and slow as the in-heap data increases.

As a result of these factors using the filesystem and relying on pagecache is superior to maintaining an in-memory cache or other structure—we at least double the available cache by having automatic access to all free memory, and likely double again by storing a compact byte structure rather than individual objects. Doing so will result in a cache of up to 28-30GB on a 32GB machine without GC penalties. Furthermore this cache will stay warm even if the service is restarted, whereas the in-process cache will need to be rebuilt in memory (which for a 10GB cache may take 10 minutes) or else it will need to start with a completely cold cache (which likely means terrible initial performance). This also greatly simplifies the code as all logic for maintaining coherency between the cache and filesystem is now in the OS, which tends to do so more efficiently and more correctly than one-off in-process attempts. If your disk usage favors linear reads then read-ahead is effectively pre-populating this cache with useful data on each disk read.

This suggests a design which is very simple: rather than maintain as much as possible in-memory and flush it all out to the filesystem in a panic when we run out of space, we invert that. All data is immediately written to a persistent log on the filesystem without necessarily flushing to disk. In effect this just means that it is transferred into the kernel's pagecache.

This style of pagecache-centric design is described in an article on the design of Varnish here (along with a healthy dose of arrogance).

Constant Time Suffices

The persistent data structure used in messaging systems are often a per-consumer queue with an associated BTree or other general-purpose random access data structures to maintain metadata about messages. BTrees are the most versatile data structure available, and make it possible to support a wide variety of transactional and non-transactional semantics in the messaging system. They do come with a fairly high cost, though: Btree operations are O(log N). Normally O(log N) is considered essentially equivalent to constant time, but this is not true for disk operations. Disk seeks come at 10 ms a pop, and each disk can do only one seek at a time so parallelism is limited. Hence even a handful of disk seeks leads to very high overhead. Since storage systems mix very fast cached operations with very slow physical disk operations, the observed performance of tree structures is often superlinear as data increases with fixed cache--i.e. doubling your data makes things much worse then twice as slow.

Intuitively a persistent queue could be built on simple reads and appends to files as is commonly the case with logging solutions. This structure has the advantage that all operations are O(1) and reads do not block writes or each other. This has obvious performance advantages since the performance is completely decoupled from the data size—one server can now take full advantage of a number of cheap, low-rotational speed 1+TB SATA drives. Though they have poor seek performance, these drives have acceptable performance for large reads and writes and come at 1/3 the price and 3x the capacity.

Having access to virtually unlimited disk space without any performance penalty means that we can provide some features not usually found in a messaging system. For example, in Kafka, instead of attempting to delete messages as soon as they are consumed, we can retain messages for a relatively long period (say a week). This leads to a great deal of flexibility for consumers, as we will describe.

4.3効率

We have put significant effort into efficiency. One of our primary use cases is handling web activity data, which is very high volume: each page view may generate dozens of writes. Furthermore we assume each message published is read by at least one consumer (often many), hence we strive to make consumption as cheap as possible.

We have also found, from experience building and running a number of similar systems, that efficiency is a key to effective multi-tenant operations. If the downstream infrastructure service can easily become a bottleneck due to a small bump in usage by the application, such small changes will often create problems. By being very fast we help ensure that the application will tip-over under load before the infrastructure. This is particularly important when trying to run a centralized service that supports dozens or hundreds of applications on a centralized cluster as changes in usage patterns are a near-daily occurrence.

We discussed disk efficiency in the previous section. Once poor disk access patterns have been eliminated, there are two common causes of inefficiency in this type of system: too many small I/O operations, and excessive byte copying.

The small I/O problem happens both between the client and the server and in the server's own persistent operations.

To avoid this, our protocol is built around a "message set" abstraction that naturally groups messages together. This allows network requests to group messages together and amortize the overhead of the network roundtrip rather than sending a single message at a time. The server in turn appends chunks of messages to its log in one go, and the consumer fetches large linear chunks at a time.

This simple optimization produces orders of magnitude speed up. Batching leads to larger network packets, larger sequential disk operations, contiguous memory blocks, and so on, all of which allows Kafka to turn a bursty stream of random message writes into linear writes that flow to the consumers.

The other inefficiency is in byte copying. At low message rates this is not an issue, but under load the impact is significant. To avoid this we employ a standardized binary message format that is shared by the producer, the broker, and the consumer (so data chunks can be transferred without modification between them).

The message log maintained by the broker is itself just a directory of files, each populated by a sequence of message sets that have been written to disk in the same format used by the producer and consumer. Maintaining this common format allows optimization of the most important operation: network transfer of persistent log chunks. Modern unix operating systems offer a highly optimized code path for transferring data out of pagecache to a socket; in Linux this is done with the sendfile system call.

To understand the impact of sendfile, it is important to understand the common data path for transfer of data from file to socket:

  1. The operating system reads data from the disk into pagecache in kernel space
  2. The application reads the data from kernel space into a user-space buffer
  3. The application writes the data back into kernel space into a socket buffer
  4. The operating system copies the data from the socket buffer to the NIC buffer where it is sent over the network

This is clearly inefficient, there are four copies and two system calls. Using sendfile, this re-copying is avoided by allowing the OS to send the data from pagecache to the network directly. So in this optimized path, only the final copy to the NIC buffer is needed.

We expect a common use case to be multiple consumers on a topic. Using the zero-copy optimization above, data is copied into pagecache exactly once and reused on each consumption instead of being stored in memory and copied out to kernel space every time it is read. This allows messages to be consumed at a rate that approaches the limit of the network connection.

This combination of pagecache and sendfile means that on a Kafka cluster where the consumers are mostly caught up you will see no read activity on the disks whatsoever as they will be serving data entirely from cache.

For more background on the sendfile and zero-copy support in Java, see this article.

End-to-end Batch Compression

In some cases the bottleneck is actually not CPU or disk but network bandwidth. This is particularly true for a data pipeline that needs to send messages between data centers over a wide-area network. Of course the user can always compress its messages one at a time without any support needed from Kafka, but this can lead to very poor compression ratios as much of the redundancy is due to repetition between messages of the same type (e.g. field names in JSON or user agents in web logs or common string values). Efficient compression requires compressing multiple messages together rather than compressing each message individually.

Kafka supports this by allowing recursive message sets. A batch of messages can be clumped together compressed and sent to the server in this form. This batch of messages will be written in compressed form and will remain compressed in the log and will only be decompressed by the consumer.

Kafka supports GZIP, Snappy and LZ4 compression protocols. More details on compression can be found here.

4.4プロデューサ

ロードバランシング

The producer sends data directly to the broker that is the leader for the partition without any intervening routing tier. To help the producer do this all Kafka nodes can answer a request for metadata about which servers are alive and where the leaders for the partitions of a topic are at any given time to allow the producer to appropriately direct its requests.

The client controls which partition it publishes messages to. This can be done at random, implementing a kind of random load balancing, or it can be done by some semantic partitioning function. We expose the interface for semantic partitioning by allowing the user to specify a key to partition by and using this to hash to a partition (there is also an option to override the partition function if need be). For example if the key chosen was a user id then all data for a given user would be sent to the same partition. This in turn will allow consumers to make locality assumptions about their consumption. This style of partitioning is explicitly designed to allow locality-sensitive processing in consumers.

Asynchronous send

Batching is one of the big drivers of efficiency, and to enable batching the Kafka producer will attempt to accumulate data in memory and to send out larger batches in a single request. The batching can be configured to accumulate no more than a fixed number of messages and to wait no longer than some fixed latency bound (say 64k or 10 ms). This allows the accumulation of more bytes to send, and few larger I/O operations on the servers. This buffering is configurable and gives a mechanism to trade off a small amount of additional latency for better throughput.

Details on configuration and the api for the producer can be found elsewhere in the documentation.

4.5コンシューマ

The Kafka consumer works by issuing "fetch" requests to the brokers leading the partitions it wants to consume. The consumer specifies its offset in the log with each request and receives back a chunk of log beginning from that position. The consumer thus has significant control over this position and can rewind it to re-consume data if need be.

Push vs. pull

An initial question we considered is whether consumers should pull data from brokers or brokers should push data to the consumer. In this respect Kafka follows a more traditional design, shared by most messaging systems, where data is pushed to the broker from the producer and pulled from the broker by the consumer. Some logging-centric systems, such as Scribe and Apache Flume, follow a very different push-based path where data is pushed downstream. There are pros and cons to both approaches. However, a push-based system has difficulty dealing with diverse consumers as the broker controls the rate at which data is transferred. The goal is generally for the consumer to be able to consume at the maximum possible rate; unfortunately, in a push system this means the consumer tends to be overwhelmed when its rate of consumption falls below the rate of production (a denial of service attack, in essence). A pull-based system has the nicer property that the consumer simply falls behind and catches up when it can. This can be mitigated with some kind of backoff protocol by which the consumer can indicate it is overwhelmed, but getting the rate of transfer to fully utilize (but never over-utilize) the consumer is trickier than it seems. Previous attempts at building systems in this fashion led us to go with a more traditional pull model.

Another advantage of a pull-based system is that it lends itself to aggressive batching of data sent to the consumer. A push-based system must choose to either send a request immediately or accumulate more data and then send it later without knowledge of whether the downstream consumer will be able to immediately process it. If tuned for low latency, this will result in sending a single message at a time only for the transfer to end up being buffered anyway, which is wasteful. A pull-based design fixes this as the consumer always pulls all available messages after its current position in the log (or up to some configurable max size). So one gets optimal batching without introducing unnecessary latency.

The deficiency of a naive pull-based system is that if the broker has no data the consumer may end up polling in a tight loop, effectively busy-waiting for data to arrive. To avoid this we have parameters in our pull request that allow the consumer request to block in a "long poll" waiting until data arrives (and optionally waiting until a given number of bytes is available to ensure large transfer sizes).

You could imagine other possible designs which would be only pull, end-to-end. The producer would locally write to a local log, and brokers would pull from that with consumers pulling from them. A similar type of "store-and-forward" producer is often proposed. This is intriguing but we felt not very suitable for our target use cases which have thousands of producers. Our experience running persistent data systems at scale led us to feel that involving thousands of disks in the system across many applications would not actually make things more reliable and would be a nightmare to operate. And in practice we have found that we can run a pipeline with strong SLAs at large scale without a need for producer persistence.

Consumer Position

Keeping track of what has been consumed is, surprisingly, one of the key performance points of a messaging system.

Most messaging systems keep metadata about what messages have been consumed on the broker. That is, as a message is handed out to a consumer, the broker either records that fact locally immediately or it may wait for acknowledgement from the consumer. This is a fairly intuitive choice, and indeed for a single machine server it is not clear where else this state could go. Since the data structures used for storage in many messaging systems scale poorly, this is also a pragmatic choice--since the broker knows what is consumed it can immediately delete it, keeping the data size small.

What is perhaps not obvious is that getting the broker and consumer to come into agreement about what has been consumed is not a trivial problem. If the broker records a message as consumed immediately every time it is handed out over the network, then if the consumer fails to process the message (say because it crashes or the request times out or whatever) that message will be lost. To solve this problem, many messaging systems add an acknowledgement feature which means that messages are only marked as sent not consumed when they are sent; the broker waits for a specific acknowledgement from the consumer to record the message as consumed. This strategy fixes the problem of losing messages, but creates new problems. First of all, if the consumer processes the message but fails before it can send an acknowledgement then the message will be consumed twice. The second problem is around performance, now the broker must keep multiple states about every single message (first to lock it so it is not given out a second time, and then to mark it as permanently consumed so that it can be removed). Tricky problems must be dealt with, like what to do with messages that are sent but never acknowledged.

Kafka handles this differently. Our topic is divided into a set of totally ordered partitions, each of which is consumed by one consumer at any given time. This means that the position of a consumer in each partition is just a single integer, the offset of the next message to consume. This makes the state about what has been consumed very small, just one number for each partition. This state can be periodically checkpointed. This makes the equivalent of message acknowledgements very cheap.

There is a side benefit of this decision. A consumer can deliberately rewind back to an old offset and re-consume data. This violates the common contract of a queue, but turns out to be an essential feature for many consumers. For example, if the consumer code has a bug and is discovered after some messages are consumed, the consumer can re-consume those messages once the bug is fixed.

Offline Data Load

Scalable persistence allows for the possibility of consumers that only periodically consume such as batch data loads that periodically bulk-load data into an offline system such as Hadoop or a relational data warehouse.

In the case of Hadoop we parallelize the data load by splitting the load over individual map tasks, one for each node/topic/partition combination, allowing full parallelism in the loading. Hadoop provides the task management, and tasks which fail can restart without danger of duplicate data—they simply restart from their original position.

4.6メッセージ配送セマンティクス

Now that we understand a little about how producers and consumers work, let's discuss the semantic guarantees Kafka provides between producer and consumer. Clearly there are multiple possible message delivery guarantees that could be provided:

It's worth noting that this breaks down into two problems: the durability guarantees for publishing a message and the guarantees when consuming a message.

Many systems claim to provide "exactly once" delivery semantics, but it is important to read the fine print, most of these claims are misleading (i.e. they don't translate to the case where consumers or producers can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost).

Kafka's semantics are straight-forward. When publishing a message we have a notion of the message being "committed" to the log. Once a published message is committed it will not be lost as long as one broker that replicates the partition to which this message was written remains "alive". The definition of alive as well as a description of which types of failures we attempt to handle will be described in more detail in the next section. For now let's assume a perfect, lossless broker and try to understand the guarantees to the producer and consumer. If a producer attempts to publish a message and experiences a network error it cannot be sure if this error happened before or after the message was committed. This is similar to the semantics of inserting into a database table with an autogenerated key.

These are not the strongest possible semantics for publishers. Although we cannot be sure of what happened in the case of a network error, it is possible to allow the producer to generate a sort of "primary key" that makes retrying the produce request idempotent. This feature is not trivial for a replicated system because of course it must work even (or especially) in the case of a server failure. With this feature it would suffice for the producer to retry until it receives acknowledgement of a successfully committed message at which point we would guarantee the message had been published exactly once. We hope to add this in a future Kafka version.

Not all use cases require such strong guarantees. For uses which are latency sensitive we allow the producer to specify the durability level it desires. If the producer specifies that it wants to wait on the message being committed this can take on the order of 10 ms. However the producer can also specify that it wants to perform the send completely asynchronously or that it wants to wait only until the leader (but not necessarily the followers) have the message.

Now let's describe the semantics from the point-of-view of the consumer. All replicas have the exact same log with the same offsets. The consumer controls its position in this log. If the consumer never crashed it could just store this position in memory, but if the consumer fails and we want this topic partition to be taken over by another process the new process will need to choose an appropriate position from which to start processing. Let's say the consumer reads some messages -- it has several options for processing the messages and updating its position.

  1. It can read the messages, then save its position in the log, and finally process the messages. In this case there is a possibility that the consumer process crashes after saving its position but before saving the output of its message processing. In this case the process that took over processing would start at the saved position even though a few messages prior to that position had not been processed. This corresponds to "at-most-once" semantics as in the case of a consumer failure messages may not be processed.
  2. It can read the messages, process the messages, and finally save its position. In this case there is a possibility that the consumer process crashes after processing messages but before saving its position. In this case when the new process takes over the first few messages it receives will already have been processed. This corresponds to the "at-least-once" semantics in the case of consumer failure. In many cases messages have a primary key and so the updates are idempotent (receiving the same message twice just overwrites a record with another copy of itself).
  3. So what about exactly once semantics (i.e. the thing you actually want)? The limitation here is not actually a feature of the messaging system but rather the need to co-ordinate the consumer's position with what is actually stored as output. The classic way of achieving this would be to introduce a two-phase commit between the storage for the consumer position and the storage of the consumers output. But this can be handled more simply and generally by simply letting the consumer store its offset in the same place as its output. This is better because many of the output systems a consumer might want to write to will not support a two-phase commit. As an example of this, our Hadoop ETL that populates data in HDFS stores its offsets in HDFS with the data it reads so that it is guaranteed that either data and offsets are both updated or neither is. We follow similar patterns for many other data systems which require these stronger semantics and for which the messages do not have a primary key to allow for deduplication.

So effectively Kafka guarantees at-least-once delivery by default and allows the user to implement at most once delivery by disabling retries on the producer and committing its offset prior to processing a batch of messages. Exactly-once delivery requires co-operation with the destination storage system but Kafka provides the offset which makes implementing this straight-forward.

4.7リプリケーション

Kafka replicates the log for each topic's partitions across a configurable number of servers (you can set this replication factor on a topic-by-topic basis). This allows automatic failover to these replicas when a server in the cluster fails so messages remain available in the presence of failures.

Other messaging systems provide some replication-related features, but, in our (totally biased) opinion, this appears to be a tacked-on thing, not heavily used, and with large downsides: slaves are inactive, throughput is heavily impacted, it requires fiddly manual configuration, etc. Kafka is meant to be used with replication by default—in fact we implement un-replicated topics as replicated topics where the replication factor is one.

The unit of replication is the topic partition. Under non-failure conditions, each partition in Kafka has a single leader and zero or more followers. The total number of replicas including the leader constitute the replication factor. All reads and writes go to the leader of the partition. Typically, there are many more partitions than brokers and the leaders are evenly distributed among brokers. The logs on the followers are identical to the leader's log—all have the same offsets and messages in the same order (though, of course, at any given time the leader may have a few as-yet unreplicated messages at the end of its log).

Followers consume messages from the leader just as a normal Kafka consumer would and apply them to their own log. Having the followers pull from the leader has the nice property of allowing the follower to naturally batch together log entries they are applying to their log.

As with most distributed systems automatically handling failures requires having a precise definition of what it means for a node to be "alive". For Kafka node liveness has two conditions

  1. A node must be able to maintain its session with ZooKeeper (via ZooKeeper's heartbeat mechanism)
  2. If it is a slave it must replicate the writes happening on the leader and not fall "too far" behind
We refer to nodes satisfying these two conditions as being "in sync" to avoid the vagueness of "alive" or "failed". The leader keeps track of the set of "in sync" nodes. If a follower dies, gets stuck, or falls behind, the leader will remove it from the list of in sync replicas. The determination of stuck and lagging replicas is controlled by the replica.lag.time.max.ms configuration.

In distributed systems terminology we only attempt to handle a "fail/recover" model of failures where nodes suddenly cease working and then later recover (perhaps without knowing that they have died). Kafka does not handle so-called "Byzantine" failures in which nodes produce arbitrary or malicious responses (perhaps due to bugs or foul play).

A message is considered "committed" when all in sync replicas for that partition have applied it to their log. Only committed messages are ever given out to the consumer. This means that the consumer need not worry about potentially seeing a message that could be lost if the leader fails. Producers, on the other hand, have the option of either waiting for the message to be committed or not, depending on their preference for tradeoff between latency and durability. This preference is controlled by the acks setting that the producer uses.

The guarantee that Kafka offers is that a committed message will not be lost, as long as there is at least one in sync replica alive, at all times.

Kafka will remain available in the presence of node failures after a short fail-over period, but may not remain available in the presence of network partitions.

Replicated Logs: Quorums, ISRs, and State Machines (Oh my!)

At its heart a Kafka partition is a replicated log. The replicated log is one of the most basic primitives in distributed data systems, and there are many approaches for implementing one. A replicated log can be used by other systems as a primitive for implementing other distributed systems in the state-machine style.

A replicated log models the process of coming into consensus on the order of a series of values (generally numbering the log entries 0, 1, 2, ...). There are many ways to implement this, but the simplest and fastest is with a leader who chooses the ordering of values provided to it. As long as the leader remains alive, all followers need to only copy the values and ordering the leader chooses.

Of course if leaders didn't fail we wouldn't need followers! When the leader does die we need to choose a new leader from among the followers. But followers themselves may fall behind or crash so we must ensure we choose an up-to-date follower. The fundamental guarantee a log replication algorithm must provide is that if we tell the client a message is committed, and the leader fails, the new leader we elect must also have that message. This yields a tradeoff: if the leader waits for more followers to acknowledge a message before declaring it committed then there will be more potentially electable leaders.

If you choose the number of acknowledgements required and the number of logs that must be compared to elect a leader such that there is guaranteed to be an overlap, then this is called a Quorum.

A common approach to this tradeoff is to use a majority vote for both the commit decision and the leader election. This is not what Kafka does, but let's explore it anyway to understand the tradeoffs. Let's say we have 2f+1 replicas. If f+1 replicas must receive a message prior to a commit being declared by the leader, and if we elect a new leader by electing the follower with the most complete log from at least f+1 replicas, then, with no more than f failures, the leader is guaranteed to have all committed messages. This is because among any f+1 replicas, there must be at least one replica that contains all committed messages. That replica's log will be the most complete and therefore will be selected as the new leader. There are many remaining details that each algorithm must handle (such as precisely defined what makes a log more complete, ensuring log consistency during leader failure or changing the set of servers in the replica set) but we will ignore these for now.

This majority vote approach has a very nice property: the latency is dependent on only the fastest servers. That is, if the replication factor is three, the latency is determined by the faster slave not the slower one.

There are a rich variety of algorithms in this family including ZooKeeper's Zab, Raft, and Viewstamped Replication. The most similar academic publication we are aware of to Kafka's actual implementation is PacificA from Microsoft.

The downside of majority vote is that it doesn't take many failures to leave you with no electable leaders. To tolerate one failure requires three copies of the data, and to tolerate two failures requires five copies of the data. In our experience having only enough redundancy to tolerate a single failure is not enough for a practical system, but doing every write five times, with 5x the disk space requirements and 1/5th the throughput, is not very practical for large volume data problems. This is likely why quorum algorithms more commonly appear for shared cluster configuration such as ZooKeeper but are less common for primary data storage. For example in HDFS the namenode's high-availability feature is built on a majority-vote-based journal, but this more expensive approach is not used for the data itself.

Kafka takes a slightly different approach to choosing its quorum set. Instead of majority vote, Kafka dynamically maintains a set of in-sync replicas (ISR) that are caught-up to the leader. Only members of this set are eligible for election as leader. A write to a Kafka partition is not considered committed until all in-sync replicas have received the write. This ISR set is persisted to ZooKeeper whenever it changes. Because of this, any replica in the ISR is eligible to be elected leader. This is an important factor for Kafka's usage model where there are many partitions and ensuring leadership balance is important. With this ISR model and f+1 replicas, a Kafka topic can tolerate f failures without losing committed messages.

For most use cases we hope to handle, we think this tradeoff is a reasonable one. In practice, to tolerate f failures, both the majority vote and the ISR approach will wait for the same number of replicas to acknowledge before committing a message (e.g. to survive one failure a majority quorum needs three replicas and one acknowledgement and the ISR approach requires two replicas and one acknowledgement). The ability to commit without the slowest servers is an advantage of the majority vote approach. However, we think it is ameliorated by allowing the client to choose whether they block on the message commit or not, and the additional throughput and disk space due to the lower required replication factor is worth it.

Another important design distinction is that Kafka does not require that crashed nodes recover with all their data intact. It is not uncommon for replication algorithms in this space to depend on the existence of "stable storage" that cannot be lost in any failure-recovery scenario without potential consistency violations. There are two primary problems with this assumption. First, disk errors are the most common problem we observe in real operation of persistent data systems and they often do not leave data intact. Secondly, even if this were not a problem, we do not want to require the use of fsync on every write for our consistency guarantees as this can reduce performance by two to three orders of magnitude. Our protocol for allowing a replica to rejoin the ISR ensures that before rejoining, it must fully re-sync again even if it lost unflushed data in its crash.

Unclean leader election: What if they all die?

Note that Kafka's guarantee with respect to data loss is predicated on at least one replica remaining in sync. If all the nodes replicating a partition die, this guarantee no longer holds.

However a practical system needs to do something reasonable when all the replicas die. If you are unlucky enough to have this occur, it is important to consider what will happen. There are two behaviors that could be implemented:

  1. Wait for a replica in the ISR to come back to life and choose this replica as the leader (hopefully it still has all its data).
  2. Choose the first replica (not necessarily in the ISR) that comes back to life as the leader.

This is a simple tradeoff between availability and consistency. If we wait for replicas in the ISR, then we will remain unavailable as long as those replicas are down. If such replicas were destroyed or their data was lost, then we are permanently down. If, on the other hand, a non-in-sync replica comes back to life and we allow it to become leader, then its log becomes the source of truth even though it is not guaranteed to have every committed message. By default Kafka chooses the second strategy and favor choosing a potentially inconsistent replica when all replicas in the ISR are dead. This behavior can be disabled using configuration property unclean.leader.election.enable, to support use cases where downtime is preferable to inconsistency.

This dilemma is not specific to Kafka. It exists in any quorum-based scheme. For example in a majority voting scheme, if a majority of servers suffer a permanent failure, then you must either choose to lose 100% of your data or violate consistency by taking what remains on an existing server as your new source of truth.

Availability and Durability Guarantees

When writing to Kafka, producers can choose whether they wait for the message to be acknowledged by 0,1 or all (-1) replicas. Note that "acknowledgement by all replicas" does not guarantee that the full set of assigned replicas have received the message. By default, when acks=all, acknowledgement happens as soon as all the current in-sync replicas have received the message. For example, if a topic is configured with only two replicas and one fails (i.e., only one in sync replica remains), then writes that specify acks=all will succeed. However, these writes could be lost if the remaining replica also fails. Although this ensures maximum availability of the partition, this behavior may be undesirable to some users who prefer durability over availability. Therefore, we provide two topic-level configurations that can be used to prefer message durability over availability:
  1. Disable unclean leader election - if all replicas become unavailable, then the partition will remain unavailable until the most recent leader becomes available again. This effectively prefers unavailability over the risk of message loss. See the previous section on Unclean Leader Election for clarification.
  2. Specify a minimum ISR size - the partition will only accept writes if the size of the ISR is above a certain minimum, in order to prevent the loss of messages that were written to just a single replica, which subsequently becomes unavailable. This setting only takes effect if the producer uses acks=all and guarantees that the message will be acknowledged by at least this many in-sync replicas. This setting offers a trade-off between consistency and availability. A higher setting for minimum ISR size guarantees better consistency since the message is guaranteed to be written to more replicas which reduces the probability that it will be lost. However, it reduces availability since the partition will be unavailable for writes if the number of in-sync replicas drops below the minimum threshold.

Replica Management

The above discussion on replicated logs really covers only a single log, i.e. one topic partition. However a Kafka cluster will manage hundreds or thousands of these partitions. We attempt to balance partitions within a cluster in a round-robin fashion to avoid clustering all partitions for high-volume topics on a small number of nodes. Likewise we try to balance leadership so that each node is the leader for a proportional share of its partitions.

It is also important to optimize the leadership election process as that is the critical window of unavailability. A naive implementation of leader election would end up running an election per partition for all partitions a node hosted when that node failed. Instead, we elect one of the brokers as the "controller". This controller detects failures at the broker level and is responsible for changing the leader of all affected partitions in a failed broker. The result is that we are able to batch together many of the required leadership change notifications which makes the election process far cheaper and faster for a large number of partitions. If the controller fails, one of the surviving brokers will become the new controller.

4.8ログの圧縮

Log compaction ensures that Kafka will always retain at least the last known value for each message key within the log of data for a single topic partition. It addresses use cases and scenarios such as restoring state after application crashes or system failure, or reloading caches after application restarts during operational maintenance. Let's dive into these use cases in more detail and then describe how compaction works.

So far we have described only the simpler approach to data retention where old log data is discarded after a fixed period of time or when the log reaches some predetermined size. This works well for temporal event data such as logging where each record stands alone. However an important class of data streams are the log of changes to keyed, mutable data (for example, the changes to a database table).

Let's discuss a concrete example of such a stream. Say we have a topic containing user email addresses; every time a user updates their email address we send a message to this topic using their user id as the primary key. Now say we send the following messages over some time period for a user with id 123, each message corresponding to a change in email address (messages for other ids are omitted):

    123 => bill@microsoft.com
            .
            .
            .
    123 => bill@gatesfoundation.org
            .
            .
            .
    123 => bill@gmail.com
Log compaction gives us a more granular retention mechanism so that we are guaranteed to retain at least the last update for each primary key (e.g. bill@gmail.com). By doing this we guarantee that the log contains a full snapshot of the final value for every key not just keys that changed recently. This means downstream consumers can restore their own state off this topic without us having to retain a complete log of all changes.

Let's start by looking at a few use cases where this is useful, then we'll see how it can be used.

  1. Database change subscription. It is often necessary to have a data set in multiple data systems, and often one of these systems is a database of some kind (either a RDBMS or perhaps a new-fangled key-value store). For example you might have a database, a cache, a search cluster, and a Hadoop cluster. Each change to the database will need to be reflected in the cache, the search cluster, and eventually in Hadoop. In the case that one is only handling the real-time updates you only need recent log. But if you want to be able to reload the cache or restore a failed search node you may need a complete data set.
  2. Event sourcing. This is a style of application design which co-locates query processing with application design and uses a log of changes as the primary store for the application.
  3. Journaling for high-availability. A process that does local computation can be made fault-tolerant by logging out changes that it makes to it's local state so another process can reload these changes and carry on if it should fail. A concrete example of this is handling counts, aggregations, and other "group by"-like processing in a stream query system. Samza, a real-time stream-processing framework, uses this feature for exactly this purpose.
In each of these cases one needs primarily to handle the real-time feed of changes, but occasionally, when a machine crashes or data needs to be re-loaded or re-processed, one needs to do a full load. Log compaction allows feeding both of these use cases off the same backing topic. This style of usage of a log is described in more detail in this blog post.

The general idea is quite simple. If we had infinite log retention, and we logged each change in the above cases, then we would have captured the state of the system at each time from when it first began. Using this complete log, we could restore to any point in time by replaying the first N records in the log. This hypothetical complete log is not very practical for systems that update a single record many times as the log will grow without bound even for a stable dataset. The simple log retention mechanism which throws away old updates will bound space but the log is no longer a way to restore the current state—now restoring from the beginning of the log no longer recreates the current state as old updates may not be captured at all.

Log compaction is a mechanism to give finer-grained per-record retention, rather than the coarser-grained time-based retention. The idea is to selectively remove records where we have a more recent update with the same primary key. This way the log is guaranteed to have at least the last state for each key.

This retention policy can be set per-topic, so a single cluster can have some topics where retention is enforced by size or time and other topics where retention is enforced by compaction.

This functionality is inspired by one of LinkedIn's oldest and most successful pieces of infrastructure—a database changelog caching service called Databus. Unlike most log-structured storage systems Kafka is built for subscription and organizes data for fast linear reads and writes. Unlike Databus, Kafka acts as a source-of-truth store so it is useful even in situations where the upstream data source would not otherwise be replayable.

Log Compaction Basics

Here is a high-level picture that shows the logical structure of a Kafka log with the offset for each message.

The head of the log is identical to a traditional Kafka log. It has dense, sequential offsets and retains all messages. Log compaction adds an option for handling the tail of the log. The picture above shows a log with a compacted tail. Note that the messages in the tail of the log retain the original offset assigned when they were first written—that never changes. Note also that all offsets remain valid positions in the log, even if the message with that offset has been compacted away; in this case this position is indistinguishable from the next highest offset that does appear in the log. For example, in the picture above the offsets 36, 37, and 38 are all equivalent positions and a read beginning at any of these offsets would return a message set beginning with 38.

Compaction also allows for deletes. A message with a key and a null payload will be treated as a delete from the log. This delete marker will cause any prior message with that key to be removed (as would any new message with that key), but delete markers are special in that they will themselves be cleaned out of the log after a period of time to free up space. The point in time at which deletes are no longer retained is marked as the "delete retention point" in the above diagram.

The compaction is done in the background by periodically recopying log segments. Cleaning does not block reads and can be throttled to use no more than a configurable amount of I/O throughput to avoid impacting producers and consumers. The actual process of compacting a log segment looks something like this:

What guarantees does log compaction provide?

Log compaction guarantees the following:
  1. Any consumer that stays caught-up to within the head of the log will see every message that is written; these messages will have sequential offsets.
  2. Ordering of messages is always maintained. Compaction will never re-order messages, just remove some.
  3. The offset for a message never changes. It is the permanent identifier for a position in the log.
  4. Any read progressing from offset 0 will see at least the final state of all records in the order they were written. All delete markers for deleted records will be seen provided the reader reaches the head of the log in a time period less than the topic's delete.retention.ms setting (the default is 24 hours). This is important as delete marker removal happens concurrently with read (and thus it is important that we not remove any delete marker prior to the reader seeing it).
  5. Any consumer progressing from the start of the log will see at least the final state of all records in the order they were written. All delete markers for deleted records will be seen provided the consumer reaches the head of the log in a time period less than the topic's delete.retention.ms setting (the default is 24 hours). This is important as delete marker removal happens concurrently with read, and thus it is important that we do not remove any delete marker prior to the consumer seeing it.

Log Compaction Details

Log compaction is handled by the log cleaner, a pool of background threads that recopy log segment files, removing records whose key appears in the head of the log. Each compactor thread works as follows:
  1. It chooses the log that has the highest ratio of log head to log tail
  2. It creates a succinct summary of the last offset for each key in the head of the log
  3. It recopies the log from beginning to end removing keys which have a later occurrence in the log. New, clean segments are swapped into the log immediately so the additional disk space required is just one additional log segment (not a fully copy of the log).
  4. The summary of the log head is essentially just a space-compact hash table. It uses exactly 24 bytes per entry. As a result with 8GB of cleaner buffer one cleaner iteration can clean around 366GB of log head (assuming 1k messages).

Configuring The Log Cleaner

The log cleaner is disabled by default. To enable it set the server config
  log.cleaner.enable=true
This will start the pool of cleaner threads. To enable log cleaning on a particular topic you can add the log-specific property
  log.cleanup.policy=compact
This can be done either at topic creation time or using the alter topic command.

Further cleaner configurations are described here.

Log Compaction Limitations

  1. You cannot configure yet how much log is retained without compaction (the "head" of the log). Currently all segments are eligible except for the last segment, i.e. the one currently being written to.

4.9クォータ

Starting in 0.9, the Kafka cluster has the ability to enforce quotas on produce and fetch requests. Quotas are basically byte-rate thresholds defined per client-id. A client-id logically identifies an application making a request. Hence a single client-id can span multiple producer and consumer instances and the quota will apply for all of them as a single entity i.e. if client-id="test-client" has a produce quota of 10MB/sec, this is shared across all instances with that same id.

Why are quotas necessary?

It is possible for producers and consumers to produce/consume very high volumes of data and thus monopolize broker resources, cause network saturation and generally DOS other clients and the brokers themselves. Having quotas protects against these issues and is all the more important in large multi-tenant clusters where a small set of badly behaved clients can degrade user experience for the well behaved ones. In fact, when running Kafka as a service this even makes it possible to enforce API limits according to an agreed upon contract.

Enforcement

By default, each unique client-id receives a fixed quota in bytes/sec as configured by the cluster (quota.producer.default, quota.consumer.default). This quota is defined on a per-broker basis. Each client can publish/fetch a maximum of X bytes/sec per broker before it gets throttled. We decided that defining these quotas per broker is much better than having a fixed cluster wide bandwidth per client because that would require a mechanism to share client quota usage among all the brokers. This can be harder to get right than the quota implementation itself!

How does a broker react when it detects a quota violation? In our solution, the broker does not return an error rather it attempts to slow down a client exceeding its quota. It computes the amount of delay needed to bring a guilty client under it's quota and delays the response for that time. This approach keeps the quota violation transparent to clients (outside of client-side metrics). This also keeps them from having to implement any special backoff and retry behavior which can get tricky. In fact, bad client behavior (retry without backoff) can exacerbate the very problem quotas are trying to solve.

Client byte rate is measured over multiple small windows (e.g. 30 windows of 1 second each) in order to detect and correct quota violations quickly. Typically, having large measurement windows (for e.g. 10 windows of 30 seconds each) leads to large bursts of traffic followed by long delays which is not great in terms of user experience.

Quota overrides

It is possible to override the default quota for client-ids that need a higher (or even lower) quota. The mechanism is similar to the per-topic log config overrides. Client-id overrides are written to ZooKeeper under /config/clients. These overrides are read by all brokers and are effective immediately. This lets us change quotas without having to do a rolling restart of the entire cluster. See here for details.

5. 実装

5.1API 設計

Producer APIs

The Producer API that wraps the 2 low-level producers - kafka.producer.SyncProducer and kafka.producer.async.AsyncProducer.

class Producer {

  /* Sends the data, partitioned by key to the topic using either the */
  /* synchronous or the asynchronous producer */
  public void send(kafka.javaapi.producer.ProducerData<K,V> producerData);

  /* Sends a list of data, partitioned by key to the topic using either */
  /* the synchronous or the asynchronous producer */
  public void send(java.util.List<kafka.javaapi.producer.ProducerData<K,V>> producerData);

  /* Closes the producer and cleans up */
  public void close();

}
The goal is to expose all the producer functionality through a single API to the client. The new producer -

Consumer APIs

We have 2 levels of consumer APIs. The low-level "simple" API maintains a connection to a single broker and has a close correspondence to the network requests sent to the server. This API is completely stateless, with the offset being passed in on every request, allowing the user to maintain this metadata however they choose.

The high-level API hides the details of brokers from the consumer and allows consuming off the cluster of machines without concern for the underlying topology. It also maintains the state of what has been consumed. The high-level API also provides the ability to subscribe to topics that match a filter expression (i.e., either a whitelist or a blacklist regular expression).

Low-level API
class SimpleConsumer {

  /* Send fetch request to a broker and get back a set of messages. */
  public ByteBufferMessageSet fetch(FetchRequest request);

  /* Send a list of fetch requests to a broker and get back a response set. */
  public MultiFetchResponse multifetch(List<FetchRequest> fetches);

  /**
   * Get a list of valid offsets (up to maxSize) before the given time.
   * The result is a list of offsets, in descending order.
   * @param time: time in millisecs,
   *              if set to OffsetRequest$.MODULE$.LATEST_TIME(), get from the latest offset available.
   *              if set to OffsetRequest$.MODULE$.EARLIEST_TIME(), get from the earliest offset available.
   */
  public long[] getOffsetsBefore(String topic, int partition, long time, int maxNumOffsets);
}
The low-level API is used to implement the high-level API as well as being used directly for some of our offline consumers which have particular requirements around maintaining state.
High-level API

/* create a connection to the cluster */
ConsumerConnector connector = Consumer.create(consumerConfig);

interface ConsumerConnector {

  /**
   * This method is used to get a list of KafkaStreams, which are iterators over
   * MessageAndMetadata objects from which you can obtain messages and their
   * associated metadata (currently only topic).
   *  Input: a map of <topic, #streams>
   *  Output: a map of <topic, list of message streams>
   */
  public Map<String,List<KafkaStream>> createMessageStreams(Map<String,Int> topicCountMap);

  /**
   * You can also obtain a list of KafkaStreams, that iterate over messages
   * from topics that match a TopicFilter. (A TopicFilter encapsulates a
   * whitelist or a blacklist which is a standard Java regex.)
   */
  public List<KafkaStream> createMessageStreamsByFilter(
      TopicFilter topicFilter, int numStreams);

  /* Commit the offsets of all messages consumed so far. */
  public commitOffsets()

  /* Shut down the connector */
  public shutdown()
}

This API is centered around iterators, implemented by the KafkaStream class. Each KafkaStream represents the stream of messages from one or more partitions on one or more servers. Each stream is used for single threaded processing, so the client can provide the number of desired streams in the create call. Thus a stream may represent the merging of multiple server partitions (to correspond to the number of processing threads), but each partition only goes to one stream.

The createMessageStreams call registers the consumer for the topic, which results in rebalancing the consumer/broker assignment. The API encourages creating many topic streams in a single call in order to minimize this rebalancing. The createMessageStreamsByFilter call (additionally) registers watchers to discover new topics that match its filter. Note that each stream that createMessageStreamsByFilter returns may iterate over messages from multiple topics (i.e., if multiple topics are allowed by the filter).

5.2ネットワーク層

The network layer is a fairly straight-forward NIO server, and will not be described in great detail. The sendfile implementation is done by giving the MessageSet interface a writeTo method. This allows the file-backed message set to use the more efficient transferTo implementation instead of an in-process buffered write. The threading model is a single acceptor thread and N processor threads which handle a fixed number of connections each. This design has been pretty thoroughly tested elsewhere and found to be simple to implement and fast. The protocol is kept quite simple to allow for future implementation of clients in other languages.

5.3メッセージ

Messages consist of a fixed-size header, a variable length opaque key byte array and a variable length opaque value byte array. The header contains the following fields:

Leaving the key and value opaque is the right decision: there is a great deal of progress being made on serialization libraries right now, and any particular choice is unlikely to be right for all uses. Needless to say a particular application using Kafka would likely mandate a particular serialization type as part of its usage. The MessageSet interface is simply an iterator over messages with specialized methods for bulk reading and writing to an NIO Channel.

5.4 Message Format

    /**
     * 1. 4 byte CRC32 of the message
     * 2. 1 byte "magic" identifier to allow format changes, value is 0 or 1
     * 3. 1 byte "attributes" identifier to allow annotations on the message independent of the version
     *    bit 0 ~ 2 : Compression codec.
     *      0 : no compression
     *      1 : gzip
     *      2 : snappy
     *      3 : lz4
     *    bit 3 : Timestamp type
     *      0 : create time
     *      1 : log append time
     *    bit 4 ~ 7 : reserved
     * 4. (Optional) 8 byte timestamp only if "magic" identifier is greater than 0
     * 5. 4 byte key length, containing length K
     * 6. K byte key
     * 7. 4 byte payload length, containing length V
     * 8. V byte payload
     */

5.5ログ

A log for a topic named "my_topic" with two partitions consists of two directories (namely my_topic_0 and my_topic_1) populated with data files containing the messages for that topic. The format of the log files is a sequence of "log entries""; each log entry is a 4 byte integer N storing the message length which is followed by the N message bytes. Each message is uniquely identified by a 64-bit integer offset giving the byte position of the start of this message in the stream of all messages ever sent to that topic on that partition. The on-disk format of each message is given below. Each log file is named with the offset of the first message it contains. So the first file created will be 00000000000.kafka, and each additional file will have an integer name roughly S bytes from the previous file where S is the max log file size given in the configuration.

The exact binary format for messages is versioned and maintained as a standard interface so message sets can be transferred between producer, broker, and client without recopying or conversion when desirable. This format is as follows:

On-disk format of a message

offset         : 8 bytes 
message length : 4 bytes (value: 4 + 1 + 1 + 8(if magic value > 0) + 4 + K + 4 + V)
crc            : 4 bytes
magic value    : 1 byte
attributes     : 1 byte
timestamp      : 8 bytes (Only exists when magic value is greater than zero)
key length     : 4 bytes
key            : K bytes
value length   : 4 bytes
value          : V bytes

The use of the message offset as the message id is unusual. Our original idea was to use a GUID generated by the producer, and maintain a mapping from GUID to offset on each broker. But since a consumer must maintain an ID for each server, the global uniqueness of the GUID provides no value. Furthermore the complexity of maintaining the mapping from a random id to an offset requires a heavy weight index structure which must be synchronized with disk, essentially requiring a full persistent random-access data structure. Thus to simplify the lookup structure we decided to use a simple per-partition atomic counter which could be coupled with the partition id and node id to uniquely identify a message; this makes the lookup structure simpler, though multiple seeks per consumer request are still likely. However once we settled on a counter, the jump to directly using the offset seemed natural—both after all are monotonically increasing integers unique to a partition. Since the offset is hidden from the consumer API this decision is ultimately an implementation detail and we went with the more efficient approach.

Writes

The log allows serial appends which always go to the last file. This file is rolled over to a fresh file when it reaches a configurable size (say 1GB). The log takes two configuration parameters: M, which gives the number of messages to write before forcing the OS to flush the file to disk, and S, which gives a number of seconds after which a flush is forced. This gives a durability guarantee of losing at most M messages or S seconds of data in the event of a system crash.

Reads

Reads are done by giving the 64-bit logical offset of a message and an S-byte max chunk size. This will return an iterator over the messages contained in the S-byte buffer. S is intended to be larger than any single message, but in the event of an abnormally large message, the read can be retried multiple times, each time doubling the buffer size, until the message is read successfully. A maximum message and buffer size can be specified to make the server reject messages larger than some size, and to give a bound to the client on the maximum it needs to ever read to get a complete message. It is likely that the read buffer ends with a partial message, this is easily detected by the size delimiting.

The actual process of reading from an offset requires first locating the log segment file in which the data is stored, calculating the file-specific offset from the global offset value, and then reading from that file offset. The search is done as a simple binary search variation against an in-memory range maintained for each file.

The log provides the capability of getting the most recently written message to allow clients to start subscribing as of "right now". This is also useful in the case the consumer fails to consume its data within its SLA-specified number of days. In this case when the client attempts to consume a non-existent offset it is given an OutOfRangeException and can either reset itself or fail as appropriate to the use case.

The following is the format of the results sent to the consumer.

MessageSetSend (fetch result)

total length     : 4 bytes
error code       : 2 bytes
message 1        : x bytes
...
message n        : x bytes
MultiMessageSetSend (multiFetch result)

total length       : 4 bytes
error code         : 2 bytes
messageSetSend 1
...
messageSetSend n

Deletes

Data is deleted one log segment at a time. The log manager allows pluggable delete policies to choose which files are eligible for deletion. The current policy deletes any log with a modification time of more than N days ago, though a policy which retained the last N GB could also be useful. To avoid locking reads while still allowing deletes that modify the segment list we use a copy-on-write style segment list implementation that provides consistent views to allow a binary search to proceed on an immutable static snapshot view of the log segments while deletes are progressing.

保証

The log provides a configuration parameter M which controls the maximum number of messages that are written before forcing a flush to disk. On startup a log recovery process is run that iterates over all messages in the newest log segment and verifies that each message entry is valid. A message entry is valid if the sum of its size and offset are less than the length of the file AND the CRC32 of the message payload matches the CRC stored with the message. In the event corruption is detected the log is truncated to the last valid offset.

Note that two kinds of corruption must be handled: truncation in which an unwritten block is lost due to a crash, and corruption in which a nonsense block is ADDED to the file. The reason for this is that in general the OS makes no guarantee of the write order between the file inode and the actual block data so in addition to losing written data the file can gain nonsense data if the inode is updated with a new size but a crash occurs before the block containing that data is written. The CRC detects this corner case, and prevents it from corrupting the log (though the unwritten messages are, of course, lost).

5.6分散

Consumer Offset Tracking

The high-level consumer tracks the maximum offset it has consumed in each partition and periodically commits its offset vector so that it can resume from those offsets in the event of a restart. Kafka provides the option to store all the offsets for a given consumer group in a designated broker (for that group) called the offset manager. i.e., any consumer instance in that consumer group should send its offset commits and fetches to that offset manager (broker). The high-level consumer handles this automatically. If you use the simple consumer you will need to manage offsets manually. This is currently unsupported in the Java simple consumer which can only commit or fetch offsets in ZooKeeper. If you use the Scala simple consumer you can discover the offset manager and explicitly commit or fetch offsets to the offset manager. A consumer can look up its offset manager by issuing a GroupCoordinatorRequest to any Kafka broker and reading the GroupCoordinatorResponse which will contain the offset manager. The consumer can then proceed to commit or fetch offsets from the offsets manager broker. In case the offset manager moves, the consumer will need to rediscover the offset manager. If you wish to manage your offsets manually, you can take a look at these code samples that explain how to issue OffsetCommitRequest and OffsetFetchRequest.

When the offset manager receives an OffsetCommitRequest, it appends the request to a special compacted Kafka topic named __consumer_offsets. The offset manager sends a successful offset commit response to the consumer only after all the replicas of the offsets topic receive the offsets. In case the offsets fail to replicate within a configurable timeout, the offset commit will fail and the consumer may retry the commit after backing off. (This is done automatically by the high-level consumer.) The brokers periodically compact the offsets topic since it only needs to maintain the most recent offset commit per partition. The offset manager also caches the offsets in an in-memory table in order to serve offset fetches quickly.

When the offset manager receives an offset fetch request, it simply returns the last committed offset vector from the offsets cache. In case the offset manager was just started or if it just became the offset manager for a new set of consumer groups (by becoming a leader for a partition of the offsets topic), it may need to load the offsets topic partition into the cache. In this case, the offset fetch will fail with an OffsetsLoadInProgress exception and the consumer may retry the OffsetFetchRequest after backing off. (This is done automatically by the high-level consumer.)

Migrating offsets from ZooKeeper to Kafka

Kafka consumers in earlier releases store their offsets by default in ZooKeeper. It is possible to migrate these consumers to commit offsets into Kafka by following these steps:

  1. Set offsets.storage=kafka and dual.commit.enabled=true in your consumer config.
  2. Do a rolling bounce of your consumers and then verify that your consumers are healthy.
  3. Set dual.commit.enabled=false in your consumer config.
  4. Do a rolling bounce of your consumers and then verify that your consumers are healthy.
A roll-back (i.e., migrating from Kafka back to ZooKeeper) can also be performed using the above steps if you set offsets.storage=zookeeper.

ZooKeeper Directories

The following gives the ZooKeeper structures and algorithms used for co-ordination between consumers and brokers.

表記法

When an element in a path is denoted [xyz], that means that the value of xyz is not fixed and there is in fact a ZooKeeper znode for each possible value of xyz. For example /topics/[topic] would be a directory named /topics containing a sub-directory for each topic name. Numerical ranges are also given such as [0...5] to indicate the subdirectories 0, 1, 2, 3, 4. An arrow -> is used to indicate the contents of a znode. For example /hello -> world would indicate a znode /hello containing the value "world".

Broker Node Registry

/brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)

This is a list of all present broker nodes, each of which provides a unique logical broker id which identifies it to consumers (which must be given as part of its configuration). On startup, a broker node registers itself by creating a znode with the logical broker id under /brokers/ids. The purpose of the logical broker id is to allow a broker to be moved to a different physical machine without affecting consumers. An attempt to register a broker id that is already in use (say because two servers are configured with the same broker id) results in an error.

Since the broker registers itself in ZooKeeper using ephemeral znodes, this registration is dynamic and will disappear if the broker is shutdown or dies (thus notifying consumers it is no longer available).

Broker Topic Registry

/brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)

Each broker registers itself under the topics it maintains and stores the number of partitions for that topic.

Consumers and Consumer Groups

Consumers of topics also register themselves in ZooKeeper, in order to coordinate with each other and balance the consumption of data. Consumers can also store their offsets in ZooKeeper by setting offsets.storage=zookeeper. However, this offset storage mechanism will be deprecated in a future release. Therefore, it is recommended to migrate offsets storage to Kafka.

Multiple consumers can form a group and jointly consume a single topic. Each consumer in the same group is given a shared group_id. For example if one consumer is your foobar process, which is run across three machines, then you might assign this group of consumers the id "foobar". This group id is provided in the configuration of the consumer, and is your way to tell the consumer which group it belongs to.

The consumers in a group divide up the partitions as fairly as possible, each partition is consumed by exactly one consumer in a consumer group.

Consumer Id Registry

In addition to the group_id which is shared by all consumers in a group, each consumer is given a transient, unique consumer_id (of the form hostname:uuid) for identification purposes. Consumer ids are registered in the following directory.

/consumers/[group_id]/ids/[consumer_id] --> {"version":...,"subscription":{...:...},"pattern":...,"timestamp":...} (ephemeral node)
Each of the consumers in the group registers under its group and creates a znode with its consumer_id. The value of the znode contains a map of <topic, #streams>. This id is simply used to identify each of the consumers which is currently active within a group. This is an ephemeral node so it will disappear if the consumer process dies.

Consumer Offsets

Consumers track the maximum offset they have consumed in each partition. This value is stored in a ZooKeeper directory if offsets.storage=zookeeper.

/consumers/[group_id]/offsets/[topic]/[partition_id] --> offset_counter_value ((persistent node)

Partition Owner registry

Each broker partition is consumed by a single consumer within a given consumer group. The consumer must establish its ownership of a given partition before any consumption can begin. To establish its ownership, a consumer writes its own id in an ephemeral node under the particular broker partition it is claiming.

/consumers/[group_id]/owners/[topic]/[partition_id] --> consumer_node_id (ephemeral node)

Broker node registration

The broker nodes are basically independent, so they only publish information about what they have. When a broker joins, it registers itself under the broker node registry directory and writes information about its host name and port. The broker also register the list of existing topics and their logical partitions in the broker topic registry. New topics are registered dynamically when they are created on the broker.

Consumer registration algorithm

When a consumer starts, it does the following:

  1. Register itself in the consumer id registry under its group.
  2. Register a watch on changes (new consumers joining or any existing consumers leaving) under the consumer id registry. (Each change triggers rebalancing among all consumers within the group to which the changed consumer belongs.)
  3. Register a watch on changes (new brokers joining or any existing brokers leaving) under the broker id registry. (Each change triggers rebalancing among all consumers in all consumer groups.)
  4. If the consumer creates a message stream using a topic filter, it also registers a watch on changes (new topics being added) under the broker topic registry. (Each change will trigger re-evaluation of the available topics to determine which topics are allowed by the topic filter. A new allowed topic will trigger rebalancing among all consumers within the consumer group.)
  5. Force itself to rebalance within in its consumer group.

Consumer rebalancing algorithm

The consumer rebalancing algorithms allows all the consumers in a group to come into consensus on which consumer is consuming which partitions. Consumer rebalancing is triggered on each addition or removal of both broker nodes and other consumers within the same group. For a given topic and a given consumer group, broker partitions are divided evenly among consumers within the group. A partition is always consumed by a single consumer. This design simplifies the implementation. Had we allowed a partition to be concurrently consumed by multiple consumers, there would be contention on the partition and some kind of locking would be required. If there are more consumers than partitions, some consumers won't get any data at all. During rebalancing, we try to assign partitions to consumers in such a way that reduces the number of broker nodes each consumer has to connect to.

Each consumer does the following during rebalancing:

   1. For each topic T that Ci subscribes to
   2.   let PT be all partitions producing topic T
   3.   let CG be all consumers in the same group as Ci that consume topic T
   4.   sort PT (so partitions on the same broker are clustered together)
   5.   sort CG
   6.   let i be the index position of Ci in CG and let N = size(PT)/size(CG)
   7.   assign partitions from i*N to (i+1)*N - 1 to consumer Ci
   8.   remove current entries owned by Ci from the partition owner registry
   9.   add newly assigned partitions to the partition owner registry
        (we may need to re-try this until the original partition owner releases its ownership)

When rebalancing is triggered at one consumer, rebalancing should be triggered in other consumers within the same group about the same time.

6. 操作

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.

6.1基本的なKafkaの操作

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 topic configurations used for auto-created topics.

Topics are added and modified using the topic tool:

 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --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 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 (no 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.

To add partitions you can do

 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --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.

To add configs:

 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --config x=y
To remove a config:
 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --delete-config x
And finally deleting a topic:
 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --delete --topic my_topic_name
Topic deletion option is disabled by default. To enable it set the server config
delete.topic.enable=true

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.

Graceful シャットダウン

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 all the partitions hosted on the broker have replicas (i.e. the replication factor is greater than 1 and 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. This means that by default 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. You can have the Kafka cluster try to restore leadership to the restored replicas by running the command:

 > bin/kafka-preferred-replica-election.sh --zookeeper zk_host:port/chroot
Since running this command can be tedious you can also configure Kafka to do this automatically by setting the following configuration:
    auto.leader.rebalance.enable=true

Balancing Replicas Across Racks

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 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.

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.

クラスタ間のデータのミラーリング

We refer to the process of replicating data between Kafka clusters "mirroring" to avoid confusion with the replication that happens amongst the nodes in a single cluster. Kafka comes with a tool for mirroring data between Kafka clusters. The tool reads from a source cluster and writes to a destination cluster, like this:

A common use case for this kind of mirroring is to provide a replica in another datacenter. This scenario will be discussed in more detail in the next section.

You can run many such mirroring processes to increase throughput and for fault-tolerance (if one process dies, the others will take overs the additional load).

Data will be read from topics in the source cluster and written to a topic with the same name in the destination cluster. In fact the mirror maker is little more than a Kafka consumer and producer hooked together.

The source and destination clusters are completely independent entities: they can have different numbers of partitions and the offsets will not be the same. For this reason the mirror cluster is not really intended as a fault-tolerance mechanism (as the consumer position will be different); for that we recommend using normal in-cluster replication. The mirror maker process will, however, retain and use the message key for partitioning so order is preserved on a per-key basis.

Here is an example showing how to mirror a single topic (named my-topic) from two input clusters:

 > bin/kafka-mirror-maker.sh
       --consumer.config consumer-1.properties --consumer.config consumer-2.properties
       --producer.config producer.properties --whitelist my-topic
Note that we specify the list of topics with the --whitelist option. This option allows any regular expression using Java-style regular expressions. So you could mirror two topics named A and B using --whitelist 'A|B'. Or you could mirror all topics using --whitelist '*'. Make sure to quote any regular expression to ensure the shell doesn't try to expand it as a file path. For convenience we allow the use of ',' instead of '|' to specify a list of topics.

Sometimes it is easier to say what it is that you don't want. Instead of using --whitelist to say what you want to mirror you can use --blacklist to say what to exclude. This also takes a regular expression argument. However, --blacklist is not supported when using --new.consumer.

Combining mirroring with the configuration auto.create.topics.enable=true makes it possible to have a replica cluster that will automatically create and replicate all data in a source cluster even as new topics are added.

コンシューマの位置の調査

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 my-group consuming a topic named my-topic would look like this:
 > bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --zookeeper localhost:2181 --group test
Group           Topic                          Pid Offset          logSize         Lag             Owner
my-group        my-topic                       0   0               0               0               test_jkreps-mn-1394154511599-60744496-0
my-group        my-topic                       1   0               0               0               test_jkreps-mn-1394154521217-1a0be913-0
Note, however, after 0.9.0, the kafka.tools.ConsumerOffsetChecker tool is deprecated and you should use the kafka.admin.ConsumerGroupCommand (or the bin/kafka-consumer-groups.sh script) to manage consumer groups, including consumers created with the new consumer API.

Managing Consumer Groups

With the ConsumerGroupCommand tool, we can list, delete, or describe consumer groups. For example, to list all consumer groups across all topics:
 > bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --list

test-consumer-group
To view offsets as in the previous example with the ConsumerOffsetChecker, we "describe" the consumer group like this:
 > bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --describe --group test-consumer-group

GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
test-consumer-group            test-foo                       0          1               3               2               test-consumer-group_postamac.local-1456198719410-29ccd54f-0
When you're using the new consumer API where the broker handles coordination of partition handling and rebalance, you can manage the groups with the "--new-consumer" flags:
 > bin/kafka-consumer-groups.sh --new-consumer --bootstrap-server broker1:9092 --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.

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 -

Automatically migrating data to new machines
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 only 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 --zookeeper localhost:2181 --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]}]
}

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 --zookeeper localhost:2181 --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 --zookeeper localhost:2181 --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
Custom partition assignment and migration
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 --zookeeper localhost:2181 --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]}]
}

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 --zookeeper localhost:2181 --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.

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 --zookeeper localhost:2181 --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]}]}

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 --zookeeper localhost:2181 --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 --zookeeper localhost:2181 --topic foo --describe
Topic:foo	PartitionCount:1	ReplicationFactor:3	Configs:
	Topic: foo	Partition: 0	Leader: 5	Replicas: 5,6,7	Isr: 5,6,7

Setting quotas

It is possible to set default quotas that apply to all client-ids by setting these configs on the brokers. By default, each client-id receives an unlimited quota. The following sets the default quota per producer and consumer client-id to 10MB/sec.
  quota.producer.default=10485760
  quota.consumer.default=10485760
It is also possible to set custom quotas for each client.
> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-name clientA --entity-type clients
Updated config for clientId: "clientA".
Here's how to describe the quota for a given client.
> ./kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-name clientA --entity-type clients
Configs for clients:clientA are producer_byte_rate=1024,consumer_byte_rate=2048

6.2データセンター

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 between clusters (see the documentation on the mirror maker tool 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 all 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 not advisable to run a single 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.

6.3 Kafka Configuration

Important Client Configurations

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

All configurations are documented in the configuration section.

A Production Server Config

Here is our server production server configuration:
# Replication configurations
num.replica.fetchers=4
replica.fetch.max.bytes=1048576
replica.fetch.wait.max.ms=500
replica.high.watermark.checkpoint.interval.ms=5000
replica.socket.timeout.ms=30000
replica.socket.receive.buffer.bytes=65536
replica.lag.time.max.ms=10000

controller.socket.timeout.ms=30000
controller.message.queue.size=10

# Log configuration
num.partitions=8
message.max.bytes=1000000
auto.create.topics.enable=true
log.index.interval.bytes=4096
log.index.size.max.bytes=10485760
log.retention.hours=168
log.flush.interval.ms=10000
log.flush.interval.messages=20000
log.flush.scheduler.interval.ms=2000
log.roll.hours=168
log.retention.check.interval.ms=300000
log.segment.bytes=1073741824

# ZK configuration
zookeeper.connection.timeout.ms=6000
zookeeper.sync.time.ms=2000

# Socket server configuration
num.io.threads=8
num.network.threads=8
socket.request.max.bytes=104857600
socket.receive.buffer.bytes=1048576
socket.send.buffer.bytes=1048576
queued.max.requests=16
fetch.purgatory.purge.interval.requests=100
producer.purgatory.purge.interval.requests=100
Our client configuration varies a fair amount between different use cases.

Java バージョン

From a security perspective, we recommend you use the latest released version of JDK 1.8 as older freely available versions have disclosed security vulnerabilities. LinkedIn is currently running JDK 1.8 u5 (looking to upgrade to a newer version) with the G1 collector. If you decide to use the G1 collector (the current default) and you are still on JDK 1.7, make sure you are on u51 or newer. LinkedIn tried out u21 in testing, but they had a number of problems with the GC implementation in that version. LinkedIn's tuning looks like this:
-Xmx6g -Xms6g -XX:MetaspaceSize=96m -XX:+UseG1GC
-XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M
-XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80
For reference, here are the stats on one of LinkedIn's busiest clusters (at peak): The tuning looks fairly aggressive, but all of the brokers in that cluster have a 90% GC pause time of about 21ms, and they're doing less than 1 young GC per second.

6.4ハードウェアとOS

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 8x7200 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).

OS

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.

You likely don't need to do much OS-level tuning though there are a few things that will help performance.

Two configurations that may be important:

Disks and Filesystem

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.

Application vs. OS Flush Management

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 it's 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.

Understanding Linux OS Flush Behavior

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.

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

Ext4の注意

Ext4 may or may not be the best filesystem for Kafka. Filesystems like XFS supposedly handle locking during fsync better. We have only tried Ext4, though.

It is not necessary to tune these settings, however those wanting to optimize performance have a few knobs that will help:

6.6監視

Kafka uses Yammer Metrics for metrics reporting in both the server and the client. This can be configured to report stats using pluggable stats reporters to hook up to your monitoring system.

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.

We do graphing and alerting on the following metrics:

解説 Mbean name Normal value
Message in rate kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec
Byte in rate kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec
Request rate kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower}
Byte out rate kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec
Log flush rate and time kafka.log:type=LogFlushStats,name=LogFlushRateAndTimeMs
# of under replicated partitions (|ISR| < |all replicas|) kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions 0
Is controller active on broker kafka.controller:type=KafkaController,name=ActiveControllerCount only one broker in the cluster should have 1
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
Partition counts kafka.server:type=ReplicaManager,name=PartitionCount mostly even across brokers
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
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=ProducerRequestPurgatory,name=PurgatorySize non-zero if ack=-1 is used
Requests waiting in the fetch purgatory kafka.server:type=FetchRequestPurgatory,name=PurgatorySize 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 waiting in the request queue kafka.network:type=RequestMetrics,name=QueueTimeMs,request={Produce|FetchConsumer|FetchFollower}
Time the request being 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 to send the response kafka.network:type=RequestMetrics,name=ResponseSendTimeMs,request={Produce|FetchConsumer|FetchFollower}
Number of messages the consumer lags behind the producer by kafka.consumer:type=ConsumerFetcherManager,name=MaxLag,clientId=([-.\w]+)
The average fraction of time the network processors are idle kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent between 0 and 1, ideally > 0.3
The average fraction of time the request handler threads are idle kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent between 0 and 1, ideally > 0.3
Quota metrics per client-id kafka.server:type={Produce|Fetch},client-id==([-.\w]+) Two attributes. throttle-time indicates the amount of time in ms the client-id was throttled. Ideally = 0. byte-rate indicates the data produce/consume rate of the client in bytes/sec.

New producer monitoring

The following metrics are available on new producer instances.
Metric/Attribute name 解説 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]+)
batch-size-avg The average number of bytes sent per partition per-request. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
batch-size-max The max number of bytes sent per partition per-request. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
compression-rate-avg The average compression rate of record batches. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-queue-time-avg The average time in ms record batches spent in the record accumulator. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-queue-time-max The maximum time in ms record batches spent in the record accumulator. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
request-latency-avg The average request latency in ms. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
request-latency-max The maximum request latency in ms. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-send-rate The average number of records sent per second. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
records-per-request-avg The average number of records per request. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-retry-rate The average per-second number of retried record sends. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-error-rate The average per-second number of record sends that resulted in errors. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-size-max The maximum record size. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
record-size-avg The average record size. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
requests-in-flight The current number of in-flight requests awaiting a response. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
metadata-age The age in seconds of the current producer metadata being used. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
connection-close-rate Connections closed per second in the window. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
connection-creation-rate New connections established per second in the window. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
network-io-rate The average number of network operations (reads or writes) on all connections per second. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
outgoing-byte-rate The average number of outgoing bytes sent per second to all servers. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
request-rate The average number of requests sent per second. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
request-size-avg The average size of all requests in the window. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
request-size-max The maximum size of any request sent in the window. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
incoming-byte-rate Bytes/second read off all sockets. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
response-rate Responses received sent per second. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
select-rate Number of times the I/O layer checked for new I/O to perform per second. kafka.producer:type=producer-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:type=producer-metrics,client-id=([-.\w]+)
io-wait-ratio The fraction of time the I/O thread spent waiting. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
io-time-ns-avg The average length of time for I/O per select call in nanoseconds. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
io-ratio The fraction of time the I/O thread spent doing I/O. kafka.producer:type=producer-metrics,client-id=([-.\w]+)
connection-count 現在のアクティブな接続の数 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
outgoing-byte-rate The average number of outgoing bytes sent per second for a node. kafka.producer:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
request-rate The average number of requests sent per second for a node. kafka.producer:type=producer-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:type=producer-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:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
incoming-byte-rate The average number of responses received per second for a node. kafka.producer:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
request-latency-avg The average request latency in ms for a node. kafka.producer:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
request-latency-max The maximum request latency in ms for a node. kafka.producer:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
response-rate Responses received sent per second for a node. kafka.producer:type=producer-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
record-send-rate The average number of records sent per second for a topic. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+),topic=([-.\w]+)
byte-rate The average number of bytes sent per second for a topic. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+),topic=([-.\w]+)
compression-rate The average compression rate of record batches for a topic. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+),topic=([-.\w]+)
record-retry-rate The average per-second number of retried record sends for a topic. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+),topic=([-.\w]+)
record-error-rate The average per-second number of record sends that resulted in errors for a topic. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+),topic=([-.\w]+)
produce-throttle-time-max The maximum time in ms a request was throttled by a broker. kafka.producer:type=producer-topic-metrics,client-id=([-.\w]+)
produce-throttle-time-avg The average time in ms a request was throttled by a broker. kafka.producer:type=producer-topic-metrics,client-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.

Audit

The final alerting we do is on the correctness of the data delivery. We audit that every message that is sent is consumed by all consumers and measure the lag for this to occur. For important topics we alert if a certain completeness is not achieved in a certain time period. The details of this are discussed in KAFKA-260.

6.7 ZooKeeper

Stable version

The current stable branch is 3.4 and the latest release of that branch is 3.4.6, which is the one ZkClient 0.7 uses. ZkClient is the client layer Kafka uses to interact with ZooKeeper.

Operationalizing ZooKeeper

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.

7. セキュリティ

7.1セキュリティ概要

In release 0.9.0.0, the Kafka community added a number of features that, used either separately or together, increases security in a Kafka cluster. These features are considered to be of beta quality. The following security measures are currently supported:
  1. Authentication of connections to brokers from clients (producers and consumers), other brokers and tools, using either SSL or SASL (Kerberos). SASL/PLAIN can also be used from release 0.10.0.0 onwards.
  2. Authentication of connections from brokers to ZooKeeper
  3. Encryption of data transferred between brokers and clients, between brokers, or between brokers and tools using SSL (Note that there is a performance degradation when SSL is enabled, the magnitude of which depends on the CPU type and the JVM implementation.)
  4. Authorization of read / write operations by clients
  5. Authorization is pluggable and integration with external authorization services is supported
It's worth noting that security is optional - non-secured clusters are supported, as well as a mix of authenticated, unauthenticated, encrypted and non-encrypted clients. The guides below explain how to configure and use the security features in both clients and brokers.

7.2SSLを使った暗号化と認証

Apache Kafka allows clients to connect over SSL. By default SSL is disabled but can be turned on as needed.
  1. Generate SSL key and certificate for each Kafka broker

    The first step of deploying HTTPS is to generate the key and the certificate for each machine in the cluster. You can use Java's keytool utility to accomplish this task. We will generate the key into a temporary keystore initially so that we can export and sign it later with CA.
            keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey
    You need to specify two parameters in the above command:
    1. keystore: the keystore file that stores the certificate. The keystore file contains the private key of the certificate; therefore, it needs to be kept safely.
    2. validity: the valid time of the certificate in days.
    Ensure that common name (CN) matches exactly with the fully qualified domain name (FQDN) of the server. The client compares the CN with the DNS domain name to ensure that it is indeed connecting to the desired server, not the malicious one.
  2. Creating your own CA

    After the first step, each machine in the cluster has a public-private key pair, and a certificate to identify the machine. The certificate, however, is unsigned, which means that an attacker can create such a certificate to pretend to be any machine.

    Therefore, it is important to prevent forged certificates by signing them for each machine in the cluster. A certificate authority (CA) is responsible for signing certificates. CA works likes a government that issues passports—the government stamps (signs) each passport so that the passport becomes difficult to forge. Other governments verify the stamps to ensure the passport is authentic. Similarly, the CA signs the certificates, and the cryptography guarantees that a signed certificate is computationally difficult to forge. Thus, as long as the CA is a genuine and trusted authority, the clients have high assurance that they are connecting to the authentic machines.

            openssl req -new -x509 -keyout ca-key -out ca-cert -days 365
    The generated CA is simply a public-private key pair and certificate, and it is intended to sign other certificates.
    The next step is to add the generated CA to the **clients' truststore** so that the clients can trust this CA:
            keytool -keystore server.truststore.jks -alias CARoot -import -file ca-cert
    Note: If you configure the Kafka brokers to require client authentication by setting ssl.client.auth to be "requested" or "required" on the Kafka brokers config then you must provide a truststore for the Kafka brokers as well and it should have all the CA certificates that clients keys were signed by.
            keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert
    In contrast to the keystore in step 1 that stores each machine's own identity, the truststore of a client stores all the certificates that the client should trust. Importing a certificate into one's truststore also means trusting all certificates that are signed by that certificate. As the analogy above, trusting the government (CA) also means trusting all passports (certificates) that it has issued. This attribute is called the chain of trust, and it is particularly useful when deploying SSL on a large Kafka cluster. You can sign all certificates in the cluster with a single CA, and have all machines share the same truststore that trusts the CA. That way all machines can authenticate all other machines.
  3. Signing the certificate

    The next step is to sign all certificates generated by step 1 with the CA generated in step 2. First, you need to export the certificate from the keystore:
            keytool -keystore server.keystore.jks -alias localhost -certreq -file cert-file
    Then sign it with the CA:
            openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed -days {validity} -CAcreateserial -passin pass:{ca-password}
    Finally, you need to import both the certificate of the CA and the signed certificate into the keystore:
            keytool -keystore server.keystore.jks -alias CARoot -import -file ca-cert
            keytool -keystore server.keystore.jks -alias localhost -import -file cert-signed
    The definitions of the parameters are the following:
    1. keystore: the location of the keystore
    2. ca-cert: the certificate of the CA
    3. ca-key: the private key of the CA
    4. ca-password: the passphrase of the CA
    5. cert-file: the exported, unsigned certificate of the server
    6. cert-signed: the signed certificate of the server
    Here is an example of a bash script with all above steps. Note that one of the commands assumes a password of `test1234`, so either use that password or edit the command before running it.
            #!/bin/bash
            #Step 1
            keytool -keystore server.keystore.jks -alias localhost -validity 365 -keyalg RSA -genkey
            #Step 2
            openssl req -new -x509 -keyout ca-key -out ca-cert -days 365
            keytool -keystore server.truststore.jks -alias CARoot -import -file ca-cert
            keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert
            #Step 3
            keytool -keystore server.keystore.jks -alias localhost -certreq -file cert-file
            openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed -days 365 -CAcreateserial -passin pass:test1234
            keytool -keystore server.keystore.jks -alias CARoot -import -file ca-cert
            keytool -keystore server.keystore.jks -alias localhost -import -file cert-signed
  4. Configuring Kafka Brokers

    Kafka Brokers support listening for connections on multiple ports. We need to configure the following property in server.properties, which must have one or more comma-separated values:
    listeners
    If SSL is not enabled for inter-broker communication (see below for how to enable it), both PLAINTEXT and SSL ports will be necessary.
            listeners=PLAINTEXT://host.name:port,SSL://host.name:port
    Following SSL configs are needed on the broker side
            ssl.keystore.location=/var/private/ssl/kafka.server.keystore.jks
            ssl.keystore.password=test1234
            ssl.key.password=test1234
            ssl.truststore.location=/var/private/ssl/kafka.server.truststore.jks
            ssl.truststore.password=test1234
    Optional settings that are worth considering:
    1. ssl.client.auth=none ("required" => client authentication is required, "requested" => client authentication is requested and client without certs can still connect. The usage of "requested" is discouraged as it provides a false sense of security and misconfigured clients will still connect successfully.)
    2. ssl.cipher.suites (Optional). A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. (Default is an empty list)
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1 (list out the SSL protocols that you are going to accept from clients. Do note that SSL is deprecated in favor of TLS and using SSL in production is not recommended)
    4. ssl.keystore.type=JKS
    5. ssl.truststore.type=JKS
    If you want to enable SSL for inter-broker communication, add the following to the broker properties file (it defaults to PLAINTEXT)
            security.inter.broker.protocol=SSL

    Due to import regulations in some countries, the Oracle implementation limits the strength of cryptographic algorithms available by default. If stronger algorithms are needed (for example, AES with 256-bit keys), the JCE Unlimited Strength Jurisdiction Policy Files must be obtained and installed in the JDK/JRE. See the JCA Providers Documentation for more information.

    Once you start the broker you should be able to see in the server.log
            with addresses: PLAINTEXT -> EndPoint(192.168.64.1,9092,PLAINTEXT),SSL -> EndPoint(192.168.64.1,9093,SSL)
    To check quickly if the server keystore and truststore are setup properly you can run the following command
    openssl s_client -debug -connect localhost:9093 -tls1
    (Note: TLSv1 should be listed under ssl.enabled.protocols)
    In the output of this command you should see server's certificate:
            -----BEGIN CERTIFICATE-----
            {variable sized random bytes}
            -----END CERTIFICATE-----
            subject=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=Sriharsha Chintalapani
            issuer=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=kafka/emailAddress=test@test.com
    If the certificate does not show up or if there are any other error messages then your keystore is not setup properly.
  5. Configuring Kafka Clients

    SSL is supported only for the new Kafka Producer and Consumer, the older API is not supported. The configs for SSL will be the same for both producer and consumer.
    If client authentication is not required in the broker, then the following is a minimal configuration example:
            security.protocol=SSL
            ssl.truststore.location=/var/private/ssl/kafka.client.truststore.jks
            ssl.truststore.password=test1234
    If client authentication is required, then a keystore must be created like in step 1 and the following must also be configured:
            ssl.keystore.location=/var/private/ssl/kafka.client.keystore.jks
            ssl.keystore.password=test1234
            ssl.key.password=test1234
    Other configuration settings that may also be needed depending on our requirements and the broker configuration:
    1. ssl.provider (Optional). SSL接続のために使われるセキュリティプロバイダの名前。デフォルト値はJVMのデフォルトのセキュリティプロバイダです。
    2. ssl.cipher.suites (Optional). A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1. It should list at least one of the protocols configured on the broker side
    4. ssl.truststore.type=JKS
    5. ssl.keystore.type=JKS

    Examples using console-producer and console-consumer:
            kafka-console-producer.sh --broker-list localhost:9093 --topic test --producer.config client-ssl.properties
            kafka-console-consumer.sh --bootstrap-server localhost:9093 --topic test --new-consumer --consumer.config client-ssl.properties

7.3SASLを使った認証

  1. SASL configuration for Kafka brokers

    1. Select one or more supported mechanisms to enable in the broker. GSSAPI and PLAIN are the mechanisms currently supported in Kafka.
    2. Add a JAAS config file for the selected mechanisms as described in the examples for setting up GSSAPI (Kerberos) or PLAIN.
    3. Pass the JAAS config file location as JVM parameter to each Kafka broker. 例えば:
          -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
    4. Configure a SASL port in server.properties, by adding at least one of SASL_PLAINTEXT or SASL_SSL to the listeners parameter, which contains one or more comma-separated values:
          listeners=SASL_PLAINTEXT://host.name:port
      If SASL_SSL is used, then SSL must also be configured. If you are only configuring a SASL port (or if you want the Kafka brokers to authenticate each other using SASL) then make sure you set the same SASL protocol for inter-broker communication:
          security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
    5. Enable one or more SASL mechanisms in server.properties:
          sasl.enabled.mechanisms=GSSAPI (,PLAIN)
    6. Configure the SASL mechanism for inter-broker communication in server.properties if using SASL for inter-broker communication:
          sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)
    7. Follow the steps in GSSAPI (Kerberos) or PLAIN to configure SASL for the enabled mechanisms. To enable multiple mechanisms in the broker, follow the steps here.
    8. Important notes:
      1. KafkaServer is the section name in the JAAS file used by each KafkaServer/Broker. This section provides SASL configuration options for the broker including any SASL client connections made by the broker for inter-broker communication.
      2. Client section is used to authenticate a SASL connection with zookeeper. It also allows the brokers to set SASL ACL on zookeeper nodes which locks these nodes down so that only the brokers can modify it. It is necessary to have the same principal name across all brokers. If you want to use a section name other than Client, set the system property zookeeper.sasl.client to the appropriate name (e.g., -Dzookeeper.sasl.client=ZkClient).
      3. ZooKeeper uses "zookeeper" as the service name by default. If you want to change this, set the system property zookeeper.sasl.client.username to the appropriate name (e.g., -Dzookeeper.sasl.client.username=zk).
  2. SASL configuration for Kafka clients

    SASL authentication is only supported for the new Java Kafka producer and consumer, the older API is not supported. To configure SASL authentication on the clients:
    1. Select a SASL mechanism for authentication.
    2. Add a JAAS config file for the selected mechanism as described in the examples for setting up GSSAPI (Kerberos) or PLAIN. KafkaClient is the section name in the JAAS file used by Kafka clients.
    3. Pass the JAAS config file location as JVM parameter to each client JVM. For example:
          -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf
    4. Configure the following properties in producer.properties or consumer.properties:
          security.protocol=SASL_PLAINTEXT (or SASL_SSL)
          sasl.mechanism=GSSAPI (or PLAIN)
    5. Follow the steps in GSSAPI (Kerberos) or PLAIN to configure SASL for the selected mechanism.
  3. Authentication using SASL/Kerberos

    1. 必要条件
      1. Kerberos
        If your organization is already using a Kerberos server (for example, by using Active Directory), there is no need to install a new server just for Kafka. Otherwise you will need to install one, your Linux vendor likely has packages for Kerberos and a short guide on how to install and configure it (Ubuntu, Redhat). Note that if you are using Oracle Java, you will need to download JCE policy files for your Java version and copy them to $JAVA_HOME/jre/lib/security.
      2. Create Kerberos Principals
        If you are using the organization's Kerberos or Active Directory server, ask your Kerberos administrator for a principal for each Kafka broker in your cluster and for every operating system user that will access Kafka with Kerberos authentication (via clients and tools).
        If you have installed your own Kerberos, you will need to create these principals yourself using the following commands:
            sudo /usr/sbin/kadmin.local -q 'addprinc -randkey kafka/{hostname}@{REALM}'
            sudo /usr/sbin/kadmin.local -q "ktadd -k /etc/security/keytabs/{keytabname}.keytab kafka/{hostname}@{REALM}"
      3. Make sure all hosts can be reachable using hostnames - it is a Kerberos requirement that all your hosts can be resolved with their FQDNs.
    2. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example (note that each broker should have its own keytab):
            KafkaServer {
                com.sun.security.auth.module.Krb5LoginModule required
                useKeyTab=true
                storeKey=true
                keyTab="/etc/security/keytabs/kafka_server.keytab"
                principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
            };
        
            // Zookeeper client authentication
            Client {
               com.sun.security.auth.module.Krb5LoginModule required
               useKeyTab=true
               storeKey=true
               keyTab="/etc/security/keytabs/kafka_server.keytab"
               principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
            };
      2. KafkaServer section in the JAAS file tells the broker which principal to use and the location of the keytab where this principal is stored. It allows the broker to login using the keytab specified in this section. See notes for more details on Zookeeper SASL configuration.
      3. Pass the JAAS and optionally the krb5 file locations as JVM parameters to each Kafka broker (see here for more details):
            -Djava.security.krb5.conf=/etc/kafka/krb5.conf
            -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      4. Make sure the keytabs configured in the JAAS file are readable by the operating system user who is starting kafka broker.
      5. Configure SASL port and SASL mechanisms in server.properties as described here. 例えば:
            listeners=SASL_PLAINTEXT://host.name:port
            security.inter.broker.protocol=SASL_PLAINTEXT
            sasl.mechanism.inter.broker.protocol=GSSAPI
            sasl.enabled.mechanisms=GSSAPI
                  
      6. We must also configure the service name in server.properties, which should match the principal name of the kafka brokers. In the above example, principal is "kafka/kafka1.hostname.com@EXAMPLE.com", so:
            sasl.kerberos.service.name=kafka
    3. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. Clients (producers, consumers, connect workers, etc) will authenticate to the cluster with their own principal (usually with the same name as the user running the client), so obtain or create these principals as needed. Then create a JAAS file for each principal. The KafkaClient section describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client using a keytab (recommended for long-running processes):
            KafkaClient {
                com.sun.security.auth.module.Krb5LoginModule required
                useKeyTab=true
                storeKey=true
                keyTab="/etc/security/keytabs/kafka_client.keytab"
                principal="kafka-client-1@EXAMPLE.COM";
            };
        For command-line utilities like kafka-console-consumer or kafka-console-producer, kinit can be used along with "useTicketCache=true" as in:
            KafkaClient {
                com.sun.security.auth.module.Krb5LoginModule required
                useTicketCache=true;
            };
      2. Pass the JAAS and optionally krb5 file locations as JVM parameters to each client JVM (see here for more details):
            -Djava.security.krb5.conf=/etc/kafka/krb5.conf
            -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf
      3. Make sure the keytabs configured in the kafka_client_jaas.conf are readable by the operating system user who is starting kafka client.
      4. Configure the following properties in producer.properties or consumer.properties:
            security.protocol=SASL_PLAINTEXT (or SASL_SSL)
            sasl.mechanism=GSSAPI
            sasl.kerberos.service.name=kafka
  4. Authentication using SASL/PLAIN

    SASL/PLAIN is a simple username/password authentication mechanism that is typically used with TLS for encryption to implement secure authentication. Kafka supports a default implementation for SASL/PLAIN which can be extended for production use as described here.

    The username is used as the authenticated Principal for configuration of ACLs etc.
    1. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example:
            KafkaServer {
                org.apache.kafka.common.security.plain.PlainLoginModule required
                username="admin"
                password="admin-secret"
                user_admin="admin-secret"
                user_alice="alice-secret";
            };
        This configuration defines two users (admin and alice). The properties username and password in the KafkaServer section are used by the broker to initiate connections to other brokers. In this example, admin is the user for inter-broker communication. The set of properties user_userName defines the passwords for all users that connect to the broker and the broker validates all client connections including those from other brokers using these properties.
      2. Pass the JAAS config file location as JVM parameter to each Kafka broker:
            -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. Configure SASL port and SASL mechanisms in server.properties as described here. 例えば:
            listeners=SASL_SSL://host.name:port
            security.inter.broker.protocol=SASL_SSL
            sasl.mechanism.inter.broker.protocol=PLAIN
            sasl.enabled.mechanisms=PLAIN
    2. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. The KafkaClient section describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client for the PLAIN mechanism:
            KafkaClient {
                org.apache.kafka.common.security.plain.PlainLoginModule required
                username="alice"
                password="alice-secret";
            };
        The properties username and password in the KafkaClient section are used by clients to configure the user for client connections. In this example, clients connect to the broker as user alice.
      2. Pass the JAAS config file location as JVM parameter to each client JVM:
            -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf
      3. Configure the following properties in producer.properties or consumer.properties:
            security.protocol=SASL_SSL
            sasl.mechanism=PLAIN
    3. Use of SASL/PLAIN in production
      • SASL/PLAIN should be used only with SSL as transport layer to ensure that clear passwords are not transmitted on the wire without encryption.
      • The default implementation of SASL/PLAIN in Kafka specifies usernames and passwords in the JAAS configuration file as shown here. To avoid storing passwords on disk, you can plugin your own implementation of javax.security.auth.spi.LoginModule that provides usernames and passwords from an external source. The login module implementation should provide username as the public credential and password as the private credential of the Subject. The default implementation org.apache.kafka.common.security.plain.PlainLoginModule can be used as an example.
      • In production systems, external authentication servers may implement password authentication. Kafka brokers can be integrated with these servers by adding your own implementation of javax.security.sasl.SaslServer. The default implementation included in Kafka in the package org.apache.kafka.common.security.plain can be used as an example to get started.
        • New providers must be installed and registered in the JVM. Providers can be installed by adding provider classes to the normal CLASSPATH or bundled as a jar file and added to JAVA_HOME/lib/ext.
        • Providers can be registered statically by adding a provider to the security properties file JAVA_HOME/lib/security/java.security.
              security.provider.n=providerClassName
          where providerClassName is the fully qualified name of the new provider and n is the preference order with lower numbers indicating higher preference.
        • Alternatively, you can register providers dynamically at runtime by invoking Security.addProvider at the beginning of the client application or in a static initializer in the login module. 例えば:
              Security.addProvider(new PlainSaslServerProvider());
        • For more details, see JCA Reference.
  5. Enabling multiple SASL mechanisms in a broker

    1. Specify configuration for the login modules of all enabled mechanisms in the KafkaServer section of the JAAS config file. 例えば:
          KafkaServer {
              com.sun.security.auth.module.Krb5LoginModule required
              useKeyTab=true
              storeKey=true
              keyTab="/etc/security/keytabs/kafka_server.keytab"
              principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
      
              org.apache.kafka.common.security.plain.PlainLoginModule required
              username="admin"
              password="admin-secret"
              user_admin="admin-secret"
              user_alice="alice-secret";
          };
    2. Enable the SASL mechanisms in server.properties:
          sasl.enabled.mechanisms=GSSAPI,PLAIN
    3. Specify the SASL security protocol and mechanism for inter-broker communication in server.properties if required:
          security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
          sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)
    4. Follow the mechanism-specific steps in GSSAPI (Kerberos) and PLAIN to configure SASL for the enabled mechanisms.
  6. Modifying SASL mechanism in a Running Cluster

    SASL mechanism can be modified in a running cluster using the following sequence:

    1. Enable new SASL mechanism by adding the mechanism to sasl.enabled.mechanisms in server.properties for each broker. Update JAAS config file to include both mechanisms as described here. Incrementally bounce the cluster nodes.
    2. Restart clients using the new mechanism.
    3. To change the mechanism of inter-broker communication (if this is required), set sasl.mechanism.inter.broker.protocol in server.properties to the new mechanism and incrementally bounce the cluster again.
    4. To remove old mechanism (if this is required), remove the old mechanism from sasl.enabled.mechanisms in server.properties and remove the entries for the old mechanism from JAAS config file. Incrementally bounce the cluster again.

7.4認証とACL

Kafka ships with a pluggable Authorizer and an out-of-box authorizer implementation that uses zookeeper to store all the acls. Kafka acls are defined in the general format of "Principal P is [Allowed/Denied] Operation O From Host H On Resource R". You can read more about the acl structure on KIP-11. In order to add, remove or list acls you can use the Kafka authorizer CLI. By default, if a Resource R has no associated acls, no one other than super users is allowed to access R. If you want to change that behavior, you can include the following in broker.properties.
allow.everyone.if.no.acl.found=true
One can also add super users in broker.properties like the following (note that the delimiter is semicolon since SSL user names may contain comma).
super.users=User:Bob;User:Alice
By default, the SSL user name will be of the form "CN=writeuser,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=Unknown". One can change that by setting a customized PrincipalBuilder in broker.properties like the following.
principal.builder.class=CustomizedPrincipalBuilderClass
By default, the SASL user name will be the primary part of the Kerberos principal. One can change that by setting sasl.kerberos.principal.to.local.rules to a customized rule in broker.properties. The format of sasl.kerberos.principal.to.local.rules is a list where each rule works in the same way as the auth_to_local in Kerberos configuration file (krb5.conf). Each rules starts with RULE: and contains an expression in the format [n:string](regexp)s/pattern/replacement/g. See the kerberos documentation for more details. An example of adding a rule to properly translate user@MYDOMAIN.COM to user while also keeping the default rule in place is:
sasl.kerberos.principal.to.local.rules=RULE:[1:$1@$0](.*@MYDOMAIN.COM)s/@.*//,DEFAULT

コマンドライン インタフェース

Kafka Authorization management CLI can be found under bin directory with all the other CLIs. The CLI script is called kafka-acls.sh. Following lists all the options that the script supports:

オプション 解説 デフォルト Option type
--add Indicates to the script that user is trying to add an acl. アクション
--remove Indicates to the script that user is trying to remove an acl. アクション
--list Indicates to the script that user is trying to list acls. アクション
--authorizer Fully qualified class name of the authorizer. kafka.security.auth.SimpleAclAuthorizer 設定
--authorizer-properties key=val pairs that will be passed to authorizer for initialization. For the default authorizer the example values are: zookeeper.connect=localhost:2181 設定
--cluster Specifies cluster as resource. リソース
--topic [topic-name] Specifies the topic as resource. リソース
--group [group-name] Specifies the consumer-group as resource. リソース
--allow-principal Principal is in PrincipalType:name format that will be added to ACL with Allow permission.
You can specify multiple --allow-principal in a single command.
Principal
--deny-principal Principal is in PrincipalType:name format that will be added to ACL with Deny permission.
You can specify multiple --deny-principal in a single command.
Principal
--allow-host IP address from which principals listed in --allow-principal will have access. if --allow-principal is specified defaults to * which translates to "all hosts" Host
--deny-host IP address from which principals listed in --deny-principal will be denied access. if --deny-principal is specified defaults to * which translates to "all hosts" Host
--operation Operation that will be allowed or denied.
Valid values are : Read, Write, Create, Delete, Alter, Describe, ClusterAction, All
All オペレーション
--producer Convenience option to add/remove acls for producer role. This will generate acls that allows WRITE, DESCRIBE on topic and CREATE on cluster. Convenience
--consumer Convenience option to add/remove acls for consumer role. This will generate acls that allows READ, DESCRIBE on topic and READ on consumer-group. Convenience

7.5実行中のクラスタでの重要なセキュリティ機能

You can secure a running cluster via one or more of the supported protocols discussed previously. This is done in phases:

The specific steps for configuring SSL and SASL are described in sections 7.2 and 7.3. Follow these steps to enable security for your desired protocol(s).

The security implementation lets you configure different protocols for both broker-client and broker-broker communication. These must be enabled in separate bounces. A PLAINTEXT port must be left open throughout so brokers and/or clients can continue to communicate.

When performing an incremental bounce stop the brokers cleanly via a SIGTERM. It's also good practice to wait for restarted replicas to return to the ISR list before moving onto the next node.

As an example, say we wish to encrypt both broker-client and broker-broker communication with SSL. In the first incremental bounce, a SSL port is opened on each node:
         listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
We then restart the clients, changing their config to point at the newly opened, secured port:
        bootstrap.servers = [broker1:9092,...]
        security.protocol = SSL
        ...etc
In the second incremental server bounce we instruct Kafka to use SSL as the broker-broker protocol (which will use the same SSL port):
        listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
        security.inter.broker.protocol=SSL
In the final bounce we secure the cluster by closing the PLAINTEXT port:
        listeners=SSL://broker1:9092
        security.inter.broker.protocol=SSL
Alternatively we might choose to open multiple ports so that different protocols can be used for broker-broker and broker-client communication. Say we wished to use SSL encryption throughout (i.e. for broker-broker and broker-client communication) but we'd like to add SASL authentication to the broker-client connection also. We would achieve this by opening two additional ports during the first bounce:
        listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
We would then restart the clients, changing their config to point at the newly opened, SASL & SSL secured port:
        bootstrap.servers = [broker1:9093,...]
        security.protocol = SASL_SSL
        ...etc
The second server bounce would switch the cluster to use encrypted broker-broker communication via the SSL port we previously opened on port 9092:
        listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
        security.inter.broker.protocol=SSL
The final bounce secures the cluster by closing the PLAINTEXT port.
       listeners=SSL://broker1:9092,SASL_SSL://broker1:9093
       security.inter.broker.protocol=SSL
ZooKeeper can be secured independently of the Kafka cluster. The steps for doing this are covered in section 7.6.2.

7.6ZooKeeper 認証

7.6.1 New clusters

To enable ZooKeeper authentication on brokers, there are two necessary steps:
  1. Create a JAAS login file and set the appropriate system property to point to it as described above
  2. Set the configuration property zookeeper.set.acl in each broker to true
The metadata stored in ZooKeeper is such that only brokers will be able to modify the corresponding znodes, but znodes are world readable. The rationale behind this decision is that the data stored in ZooKeeper is not sensitive, but inappropriate manipulation of znodes can cause cluster disruption. We also recommend limiting the access to ZooKeeper via network segmentation (only brokers and some admin tools need access to ZooKeeper if the new consumer and new producer are used).

7.6.2 Migrating clusters

If you are running a version of Kafka that does not support security or simply with security disabled, and you want to make the cluster secure, then you need to execute the following steps to enable ZooKeeper authentication with minimal disruption to your operations:
  1. Perform a rolling restart setting the JAAS login file, which enables brokers to authenticate. At the end of the rolling restart, brokers are able to manipulate znodes with strict ACLs, but they will not create znodes with those ACLs
  2. Perform a second rolling restart of brokers, this time setting the configuration parameter zookeeper.set.acl to true, which enables the use of secure ACLs when creating znodes
  3. Execute the ZkSecurityMigrator tool. To execute the tool, there is this script: ./bin/zookeeper-security-migration.sh with zookeeper.acl set to secure. This tool traverses the corresponding sub-trees changing the ACLs of the znodes

It is also possible to turn off authentication in a secure cluster. To do it, follow these steps:

  1. Perform a rolling restart of brokers setting the JAAS login file, which enables brokers to authenticate, but setting zookeeper.set.acl to false. At the end of the rolling restart, brokers stop creating znodes with secure ACLs, but are still able to authenticate and manipulate all znodes
  2. Execute the ZkSecurityMigrator tool. To execute the tool, run this script ./bin/zookeeper-security-migration.sh with zookeeper.acl set to unsecure. This tool traverses the corresponding sub-trees changing the ACLs of the znodes
  3. Perform a second rolling restart of brokers, this time omitting the system property that sets the JAAS login file
Here is an example of how to run the migration tool:
./bin/zookeeper-security-migration --zookeeper.acl=secure --zookeeper.connection=localhost:2181

Run this to see the full list of parameters:

./bin/zookeeper-security-migration --help

7.6.3 Migrating the ZooKeeper ensemble

It is also necessary to enable authentication on the ZooKeeper ensemble. To do it, we need to perform a rolling restart of the server and set a few properties. Please refer to the ZooKeeper documentation for more detail:
  1. Apache ZooKeeper documentation
  2. Apache ZooKeeper wiki

8. Kafka接続

8.1概要

Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other systems. It makes it simple to quickly define connectors that move large collections of data into and out of Kafka. Kafka Connect can ingest entire databases or collect metrics from all your application servers into Kafka topics, making the data available for stream processing with low latency. An export job can deliver data from Kafka topics into secondary storage and query systems or into batch systems for offline analysis. Kafka Connect features include:

8.2ユーザガイド

The quickstart provides a brief example of how to run a standalone version of Kafka Connect. This section describes how to configure, run, and manage Kafka Connect in more detail.

Running Kafka Connect

Kafka Connect currently supports two modes of execution: standalone (single process) and distributed. In standalone mode all work is performed in a single process. This configuration is simpler to setup and get started with and may be useful in situations where only one worker makes sense (e.g. collecting log files), but it does not benefit from some of the features of Kafka Connect such as fault tolerance. You can start a standalone process with the following command:
> bin/connect-standalone.sh config/connect-standalone.properties connector1.properties [connector2.properties ...]
The first parameter is the configuration for the worker. This includes settings such as the Kafka connection parameters, serialization format, and how frequently to commit offsets. The provided example should work well with a local cluster running with the default configuration provided by config/server.properties. It will require tweaking to use with a different configuration or production deployment. The remaining parameters are connector configuration files. You may include as many as you want, but all will execute within the same process (on different threads). Distributed mode handles automatic balancing of work, allows you to scale up (or down) dynamically, and offers fault tolerance both in the active tasks and for configuration and offset commit data. Execution is very similar to standalone mode:
> bin/connect-distributed.sh config/connect-distributed.properties
The difference is in the class which is started and the configuration parameters which change how the Kafka Connect process decides where to store configurations, how to assign work, and where to store offsets and task statues. In the distributed mode, Kafka Connect stores the offsets, configs and task statuses in Kafka topics. It is recommended to manually create the topics for offset, configs and statuses in order to achieve the desired the number of partitions and replication factors. If the topics are not yet created when starting Kafka Connect, the topics will be auto created with default number of partitions and replication factor, which may not be best suited for its usage. In particular, the following configuration parameters are critical to set before starting your cluster: Note that in distributed mode the connector configurations are not passed on the command line. Instead, use the REST API described below to create, modify, and destroy connectors.

Configuring Connectors

Connector configurations are simple key-value mappings. For standalone mode these are defined in a properties file and passed to the Connect process on the command line. In distributed mode, they will be included in the JSON payload for the request that creates (or modifies) the connector. Most configurations are connector dependent, so they can't be outlined here. However, there are a few common options: The connector.class config supports several formats: the full name or alias of the class for this connector. If the connector is org.apache.kafka.connect.file.FileStreamSinkConnector, you can either specify this full name or use FileStreamSink or FileStreamSinkConnector to make the configuration a bit shorter. Sink connectors also have one additional option to control their input: For any other options, you should consult the documentation for the connector.

REST API

Since Kafka Connect is intended to be run as a service, it also provides a REST API for managing connectors. By default this service runs on port 8083. The following are the currently supported endpoints: Kafka Connect also provides a REST API for getting information about connector plugins:

8.3コネクタ開発ガイド

This guide describes how developers can write new connectors for Kafka Connect to move data between Kafka and other systems. It briefly reviews a few key concepts and then describes how to create a simple connector.

Core Concepts and APIs

Connectors and Tasks
To copy data between Kafka and another system, users create a Connector for the system they want to pull data from or push data to. Connectors come in two flavors: SourceConnectors import data from another system (e.g. JDBCSourceConnector would import a relational database into Kafka) and SinkConnectors export data (e.g. HDFSSinkConnector would export the contents of a Kafka topic to an HDFS file). Connectors do not perform any data copying themselves: their configuration describes the data to be copied, and the Connector is responsible for breaking that job into a set of Tasks that can be distributed to workers. These Tasks also come in two corresponding flavors: SourceTask and SinkTask. With an assignment in hand, each Task must copy its subset of the data to or from Kafka. In Kafka Connect, it should always be possible to frame these assignments as a set of input and output streams consisting of records with consistent schemas. Sometimes this mapping is obvious: each file in a set of log files can be considered a stream with each parsed line forming a record using the same schema and offsets stored as byte offsets in the file. In other cases it may require more effort to map to this model: a JDBC connector can map each table to a stream, but the offset is less clear. One possible mapping uses a timestamp column to generate queries incrementally returning new data, and the last queried timestamp can be used as the offset.
Streams and Records
Each stream should be a sequence of key-value records. Both the keys and values can have complex structure -- many primitive types are provided, but arrays, objects, and nested data structures can be represented as well. The runtime data format does not assume any particular serialization format; this conversion is handled internally by the framework. In addition to the key and value, records (both those generated by sources and those delivered to sinks) have associated stream IDs and offsets. These are used by the framework to periodically commit the offsets of data that have been processed so that in the event of failures, processing can resume from the last committed offsets, avoiding unnecessary reprocessing and duplication of events.
Dynamic Connectors
Not all jobs are static, so Connector implementations are also responsible for monitoring the external system for any changes that might require reconfiguration. For example, in the JDBCSourceConnector example, the Connector might assign a set of tables to each Task. When a new table is created, it must discover this so it can assign the new table to one of the Tasks by updating its configuration. When it notices a change that requires reconfiguration (or a change in the number of Tasks), it notifies the framework and the framework updates any corresponding Tasks.

Developing a Simple Connector

Developing a connector only requires implementing two interfaces, the Connector and Task. A simple example is included with the source code for Kafka in the file package. This connector is meant for use in standalone mode and has implementations of a SourceConnector/SourceTask to read each line of a file and emit it as a record and a SinkConnector/SinkTask that writes each record to a file. The rest of this section will walk through some code to demonstrate the key steps in creating a connector, but developers should also refer to the full example source code as many details are omitted for brevity.
Connector Example
We'll cover the SourceConnector as a simple example. SinkConnector implementations are very similar. Start by creating the class that inherits from SourceConnector and add a couple of fields that will store parsed configuration information (the filename to read from and the topic to send data to):
public class FileStreamSourceConnector extends SourceConnector {
    private String filename;
    private String topic;
The easiest method to fill in is getTaskClass(), which defines the class that should be instantiated in worker processes to actually read the data:
@Override
public Class



We will define the FileStreamSourceTask class below. Next, we add some standard lifecycle methods, start() and stop():



@Override
public void start(Map<String, String> props) {
    // The complete version includes error handling as well.
    filename = props.get(FILE_CONFIG);
    topic = props.get(TOPIC_CONFIG);
}

@Override
public void stop() {
    // Nothing to do since no background monitoring is required.
}
Finally, the real core of the implementation is in getTaskConfigs(). In this case we are only handling a single file, so even though we may be permitted to generate more tasks as per the maxTasks argument, we return a list with only one entry:
@Override
public List<Map<String, String>> getTaskConfigs(int maxTasks) {
    ArrayList>Map<String, String>> configs = new ArrayList<>();
    // Only one input stream makes sense.
    Map<String, String> config = new Map<>();
    if (filename != null)
        config.put(FILE_CONFIG, filename);
    config.put(TOPIC_CONFIG, topic);
    configs.add(config);
    return configs;
}
Although not used in the example, SourceTask also provides two APIs to commit offsets in the source system: commit and commitRecord. The APIs are provided for source systems which have an acknowledgement mechanism for messages. Overriding these methods allows the source connector to acknowledge messages in the source system, either in bulk or individually, once they have been written to Kafka. The commit API stores the offsets in the source system, up to the offsets that have been returned by poll. The implementation of this API should block until the commit is complete. The commitRecord API saves the offset in the source system for each SourceRecord after it is written to Kafka. As Kafka Connect will record offsets automatically, SourceTasks are not required to implement them. In cases where a connector does need to acknowledge messages in the source system, only one of the APIs is typically required. Even with multiple tasks, this method implementation is usually pretty simple. It just has to determine the number of input tasks, which may require contacting the remote service it is pulling data from, and then divvy them up. Because some patterns for splitting work among tasks are so common, some utilities are provided in ConnectorUtils to simplify these cases. Note that this simple example does not include dynamic input. See the discussion in the next section for how to trigger updates to task configs.
Task Example - Source Task
Next we'll describe the implementation of the corresponding SourceTask. The implementation is short, but too long to cover completely in this guide. We'll use pseudo-code to describe most of the implementation, but you can refer to the source code for the full example. Just as with the connector, we need to create a class inheriting from the appropriate base Task class. It also has some standard lifecycle methods:
public class FileStreamSourceTask extends SourceTask<Object, Object> {
    String filename;
    InputStream stream;
    String topic;

    public void start(Map<String, String> props) {
        filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
        stream = openOrThrowError(filename);
        topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
    }

    @Override
    public synchronized void stop() {
        stream.close();
    }
These are slightly simplified versions, but show that that these methods should be relatively simple and the only work they should perform is allocating or freeing resources. There are two points to note about this implementation. First, the start() method does not yet handle resuming from a previous offset, which will be addressed in a later section. Second, the stop() method is synchronized. This will be necessary because SourceTasks are given a dedicated thread which they can block indefinitely, so they need to be stopped with a call from a different thread in the Worker. Next, we implement the main functionality of the task, the poll() method which gets events from the input system and returns a List<SourceRecord>:
@Override
public List<SourceRecord> poll() throws InterruptedException {
    try {
        ArrayList<SourceRecord> records = new ArrayList<>();
        while (streamValid(stream) && records.isEmpty()) {
            LineAndOffset line = readToNextLine(stream);
            if (line != null) {
                Map<String, Object> sourcePartition = Collections.singletonMap("filename", filename);
                Map<String, Object> sourceOffset = Collections.singletonMap("position", streamOffset);
                records.add(new SourceRecord(sourcePartition, sourceOffset, topic, Schema.STRING_SCHEMA, line));
            } else {
                Thread.sleep(1);
            }
        }
        return records;
    } catch (IOException e) {
        // Underlying stream was killed, probably as a result of calling stop. Allow to return
        // null, and driving thread will handle any shutdown if necessary.
    }
    return null;
}
Again, we've omitted some details, but we can see the important steps: the poll() method is going to be called repeatedly, and for each call it will loop trying to read records from the file. For each line it reads, it also tracks the file offset. It uses this information to create an output SourceRecord with four pieces of information: the source partition (there is only one, the single file being read), source offset (byte offset in the file), output topic name, and output value (the line, and we include a schema indicating this value will always be a string). Other variants of the SourceRecord constructor can also include a specific output partition and a key. Note that this implementation uses the normal Java InputStream interface and may sleep if data is not available. This is acceptable because Kafka Connect provides each task with a dedicated thread. While task implementations have to conform to the basic poll() interface, they have a lot of flexibility in how they are implemented. In this case, an NIO-based implementation would be more efficient, but this simple approach works, is quick to implement, and is compatible with older versions of Java.
Sink Tasks
The previous section described how to implement a simple SourceTask. Unlike SourceConnector and SinkConnector, SourceTask and SinkTask have very different interfaces because SourceTask uses a pull interface and SinkTask uses a push interface. Both share the common lifecycle methods, but the SinkTask interface is quite different:
public abstract class SinkTask implements Task {
    public void initialize(SinkTaskContext context) {
        this.context = context;
    }

    public abstract void put(Collection<SinkRecord> records);
     
    public abstract void flush(Map<TopicPartition, Long> offsets);
The SinkTask documentation contains full details, but this interface is nearly as simple as the SourceTask. The put() method should contain most of the implementation, accepting sets of SinkRecords, performing any required translation, and storing them in the destination system. This method does not need to ensure the data has been fully written to the destination system before returning. In fact, in many cases internal buffering will be useful so an entire batch of records can be sent at once, reducing the overhead of inserting events into the downstream data store. The SinkRecords contain essentially the same information as SourceRecords: Kafka topic, partition, offset and the event key and value. The flush() method is used during the offset commit process, which allows tasks to recover from failures and resume from a safe point such that no events will be missed. The method should push any outstanding data to the destination system and then block until the write has been acknowledged. The offsets parameter can often be ignored, but is useful in some cases where implementations want to store offset information in the destination store to provide exactly-once delivery. For example, an HDFS connector could do this and use atomic move operations to make sure the flush() operation atomically commits the data and offsets to a final location in HDFS.
Resuming from Previous Offsets
The SourceTask implementation included a stream ID (the input filename) and offset (position in the file) with each record. The framework uses this to commit offsets periodically so that in the case of a failure, the task can recover and minimize the number of events that are reprocessed and possibly duplicated (or to resume from the most recent offset if Kafka Connect was stopped gracefully, e.g. in standalone mode or due to a job reconfiguration). This commit process is completely automated by the framework, but only the connector knows how to seek back to the right position in the input stream to resume from that location. To correctly resume upon startup, the task can use the SourceContext passed into its initialize() method to access the offset data. In initialize(), we would add a bit more code to read the offset (if it exists) and seek to that position:
    stream = new FileInputStream(filename);
    Map<String, Object> offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
    if (offset != null) {
        Long lastRecordedOffset = (Long) offset.get("position");
        if (lastRecordedOffset != null)
            seekToOffset(stream, lastRecordedOffset);
    }
Of course, you might need to read many keys for each of the input streams. The OffsetStorageReader interface also allows you to issue bulk reads to efficiently load all offsets, then apply them by seeking each input stream to the appropriate position.

Dynamic Input/Output Streams

Kafka Connect is intended to define bulk data copying jobs, such as copying an entire database rather than creating many jobs to copy each table individually. One consequence of this design is that the set of input or output streams for a connector can vary over time. Source connectors need to monitor the source system for changes, e.g. table additions/deletions in a database. When they pick up changes, they should notify the framework via the ConnectorContext object that reconfiguration is necessary. For example, in a SourceConnector:
    if (inputsChanged())
        this.context.requestTaskReconfiguration();
The framework will promptly request new configuration information and update the tasks, allowing them to gracefully commit their progress before reconfiguring them. Note that in the SourceConnector this monitoring is currently left up to the connector implementation. If an extra thread is required to perform this monitoring, the connector must allocate it itself. Ideally this code for monitoring changes would be isolated to the Connector and tasks would not need to worry about them. However, changes can also affect tasks, most commonly when one of their input streams is destroyed in the input system, e.g. if a table is dropped from a database. If the Task encounters the issue before the Connector, which will be common if the Connector needs to poll for changes, the Task will need to handle the subsequent error. Thankfully, this can usually be handled simply by catching and handling the appropriate exception. SinkConnectors usually only have to handle the addition of streams, which may translate to new entries in their outputs (e.g., a new database table). The framework manages any changes to the Kafka input, such as when the set of input topics changes because of a regex subscription. SinkTasks should expect new input streams, which may require creating new resources in the downstream system, such as a new table in a database. The trickiest situation to handle in these cases may be conflicts between multiple SinkTasks seeing a new input stream for the first time and simultaneously trying to create the new resource. SinkConnectors, on the other hand, will generally require no special code for handling a dynamic set of streams.

Connect Configuration Validation

Kafka Connect allows you to validate connector configurations before submitting a connector to be executed and can provide feedback about errors and recommended values. To take advantage of this, connector developers need to provide an implementation of config() to expose the configuration definition to the framework. The following code in FileStreamSourceConnector defines the configuration and exposes it to the framework.
    private static final ConfigDef CONFIG_DEF = new ConfigDef()
        .define(FILE_CONFIG, Type.STRING, Importance.HIGH, "Source filename.")
        .define(TOPIC_CONFIG, Type.STRING, Importance.HIGH, "The topic to publish data to");

    public ConfigDef config() {
        return CONFIG_DEF;
    }
ConfigDef class is used for specifying the set of expected configurations. For each configuration, you can specify the name, the type, the default value, the documentation, the group information, the order in the group, the width of the configuration value and the name suitable for display in the UI. Plus, you can provide special validation logic used for single configuration validation by overriding the Validator class. Moreover, as there may be dependencies between configurations, for example, the valid values and visibility of a configuration may change according to the values of other configurations. To handle this, ConfigDef allows you to specify the dependents of a configuration and to provide an implementation of Recommender to get valid values and set visibility of a configuration given the current configuration values. Also, the validate() method in Connector provides a default validation implementation which returns a list of allowed configurations together with configuration errors and recommended values for each configuration. However, it does not use the recommended values for configuration validation. You may provide an override of the default implementation for customized configuration validation, which may use the recommended values.

Working with Schemas

The FileStream connectors are good examples because they are simple, but they also have trivially structured data -- each line is just a string. Almost all practical connectors will need schemas with more complex data formats. To create more complex data, you'll need to work with the Kafka Connect data API. Most structured records will need to interact with two classes in addition to primitive types: Schema and Struct. The API documentation provides a complete reference, but here is a simple example creating a Schema and Struct:
Schema schema = SchemaBuilder.struct().name(NAME)
    .field("name", Schema.STRING_SCHEMA)
    .field("age", Schema.INT_SCHEMA)
    .field("admin", new SchemaBuilder.boolean().defaultValue(false).build())
    .build();

Struct struct = new Struct(schema)
    .put("name", "Barbara Liskov")
    .put("age", 75)
    .build();
If you are implementing a source connector, you'll need to decide when and how to create schemas. Where possible, you should avoid recomputing them as much as possible. For example, if your connector is guaranteed to have a fixed schema, create it statically and reuse a single instance. However, many connectors will have dynamic schemas. One simple example of this is a database connector. Considering even just a single table, the schema will not be predefined for the entire connector (as it varies from table to table). But it also may not be fixed for a single table over the lifetime of the connector since the user may execute an ALTER TABLE command. The connector must be able to detect these changes and react appropriately. Sink connectors are usually simpler because they are consuming data and therefore do not need to create schemas. However, they should take just as much care to validate that the schemas they receive have the expected format. When the schema does not match -- usually indicating the upstream producer is generating invalid data that cannot be correctly translated to the destination system -- sink connectors should throw an exception to indicate this error to the system.

Kafka Connect Administration

Kafka Connect's REST layer provides a set of APIs to enable administration of the cluster. This includes APIs to view the configuration of connectors and the status of their tasks, as well as to alter their current behavior (e.g. changing configuration and restarting tasks).

When a connector is first submitted to the cluster, the workers rebalance the full set of connectors in the cluster and their tasks so that each worker has approximately the same amount of work. This same rebalancing procedure is also used when connectors increase or decrease the number of tasks they require, or when a connector's configuration is changed. You can use the REST API to view the current status of a connector and its tasks, including the id of the worker to which each was assigned. For example, querying the status of a file source (using GET /connectors/file-source/status) might produce output like the following:

{
  "name": "file-source",
  "connector": {
    "state": "RUNNING",
    "worker_id": "192.168.1.208:8083"
  },
  "tasks": [
    {
      "id": 0,
      "state": "RUNNING",
      "worker_id": "192.168.1.209:8083"
    }
  ]
}

Connectors and their tasks publish status updates to a shared topic (configured with status.storage.topic) which all workers in the cluster monitor. Because the workers consume this topic asynchronously, there is typically a (short) delay before a state change is visible through the status API. The following states are possible for a connector or one of its tasks:

  • UNASSIGNED: The connector/task has not yet been assigned to a worker.
  • RUNNING: The connector/task is running.
  • PAUSED: The connector/task has been administratively paused.
  • FAILED: The connector/task has failed (usually by raising an exception, which is reported in the status output).

In most cases, connector and task states will match, though they may be different for short periods of time when changes are occurring or if tasks have failed. For example, when a connector is first started, there may be a noticeable delay before the connector and its tasks have all transitioned to the RUNNING state. States will also diverge when tasks fail since Connect does not automatically restart failed tasks. To restart a connector/task manually, you can use the restart APIs listed above. Note that if you try to restart a task while a rebalance is taking place, Connect will return a 409 (Conflict) status code. You can retry after the rebalance completes, but it might not be necessary since rebalances effectively restart all the connectors and tasks in the cluster.

It's sometimes useful to temporarily stop the message processing of a connector. For example, if the remote system is undergoing maintenance, it would be preferable for source connectors to stop polling it for new data instead of filling logs with exception spam. For this use case, Connect offers a pause/resume API. While a source connector is paused, Connect will stop polling it for additional records. While a sink connector is paused, Connect will stop pushing new messages to it. The pause state is persistent, so even if you restart the cluster, the connector will not begin message processing again until the task has been resumed. Note that there may be a delay before all of a connector's tasks have transitioned to the PAUSED state since it may take time for them to finish whatever processing they were in the middle of when being paused. Additionally, failed tasks will not transition to the PAUSED state until they have been restarted.

9. Kafka ストリーム

9.1概要

Kafka Streams is a client library for processing and analyzing data stored in Kafka and either write the resulting data back to Kafka or send the final output to an external system. It builds upon important stream processing concepts such as properly distinguishing between event time and processing time, windowing support, 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.

Some highlights of Kafka Streams:

  • Designed as a simple and lightweight client library, which can be easily embedded in any Java application and integrated with any existing packaging, deployment and operational tools that users have for their streaming applications.
  • Has no external dependencies on systems other than Apache Kafka itself as the internal messaging layer; notably, it uses Kafka's partitioning model to horizontally scale processing while maintaining strong ordering guarantees.
  • Supports fault-tolerant local state, which enables very fast and efficient stateful operations like joins and windowed aggregations.
  • Employs one-record-at-a-time processing to achieve low processing latency, and supports event-time based windowing operations.
  • Offers necessary stream processing primitives, along with a high-level Streams DSL and a low-level Processor API.

9.2開発者ガイド

There is a quickstart example that provides how to run a stream processing program coded in the Kafka Streams library. This section focuses on how to write, configure, and execute a Kafka Streams application.

中核となる概念

We first summarize the key concepts of Kafka Streams.

Stream Processing Topology
  • A streamis the most important abstraction provided by Kafka Streams: it represents an unbounded, continuously updating data set. A stream is an ordered, replayable, and fault-tolerant sequence of immutable data records, where a data record is defined as a key-value pair.
  • A stream processing application written in Kafka Streams defines its computational logic through one or more processor topologies, where a processor topology is a graph of stream processors (nodes) that are connected by streams (edges).
  • A stream processor is a node in the processor topology; it represents a processing step to transform data in streams by receiving one input record at a time from its upstream processors in the topology, applying its operation to it, and may subsequently producing one or more output records to its downstream processors.

Kafka Streams offers two ways to define the stream processing topology: the Kafka Streams DSL provides the most common data transformation operations such as map and filter; the lower-level Processor API allows developers define and connect custom processors as well as to interact with state stores.

時間

A critical aspect in stream processing is the notion of time, and how it is modeled and integrated. For example, some operations such as windowing are defined based on time boundaries.

Common notions of time in streams are:

  • Event time - The point in time when an event or data record occurred, i.e. was originally created "at the source".
  • Processing time - The point in time when the event or data record happens to be processed by the stream processing application, i.e. when the record is being consumed. The processing time may be milliseconds, hours, or days etc. later than the original event time.

Kafka Streams assigns a timestamp to every data record via the TimestampExtractor interface. Concrete implementations of this interface may retrieve or compute timestamps based on the actual contents of data records such as an embedded timestamp field to provide event-time semantics, or use any other approach such as returning the current wall-clock time at the time of processing, thereby yielding processing-time semantics to stream processing applications. Developers can thus enforce different notions of time depending on their business needs. For example, per-record timestamps describe the progress of a stream with regards to time (although records may be out-of-order within the stream) and are leveraged by time-dependent operations such as joins.

States

Some stream processing applications don't require state, which means the processing of a message is independent from the processing of all other messages. However, being able to maintain state opens up many possibilities for sophisticated stream processing applications: you can join input streams, or group and aggregate data records. Many such stateful operators are provided by the Kafka Streams DSL.

Kafka Streams provides so-called state stores, which can be used by stream processing applications to store and query data. This is an important capability when implementing stateful operations. Every task in Kafka Streams embeds one or more state stores that can be accessed via APIs to store and query data required for processing. These state stores can either be a persistent key-value store, an in-memory hashmap, or another convenient data structure. Kafka Streams offers fault-tolerance and automatic recovery for local state stores.


As we have mentioned above, the computational logic of a Kafka Streams application is defined as a processor topology. Currently Kafka Streams provides two sets of APIs to define the processor topology, which will be described in the subsequent sections.

低レベルプロセッサAPI

プロセッサ

Developers can define their customized processing logic by implementing the Processor interface, which provides process and punctuate methods. The process method is performed on each of the received record; and the punctuate method is performed periodically based on elapsed time. In addition, the processor can maintain the current ProcessorContext instance variable initialized in the init method, and use the context to schedule the punctuation period (context().schedule), to forward the modified / new key-value pair to downstream processors (context().forward), to commit the current processing progress (context().commit), etc.

    public class MyProcessor extends Processor {
        private ProcessorContext context;
        private KeyValueStore kvStore;

        @Override
        @SuppressWarnings("unchecked")
        public void init(ProcessorContext context) {
            this.context = context;
            this.context.schedule(1000);
            this.kvStore = (KeyValueStore) context.getStateStore("Counts");
        }

        @Override
        public void process(String dummy, String line) {
            String[] words = line.toLowerCase().split(" ");

            for (String word : words) {
                Integer oldValue = this.kvStore.get(word);

                if (oldValue == null) {
                    this.kvStore.put(word, 1);
                } else {
                    this.kvStore.put(word, oldValue + 1);
                }
            }
        }

        @Override
        public void punctuate(long timestamp) {
            KeyValueIterator iter = this.kvStore.all();

            while (iter.hasNext()) {
                KeyValue entry = iter.next();
                context.forward(entry.key, entry.value.toString());
            }

            iter.close();
            context.commit();
        }

        @Override
        public void close() {
            this.kvStore.close();
        }
    };

In the above implementation, the following actions are performed:

  • In the init method, schedule the punctuation every 1 second and retrieve the local state store by its name "Counts".
  • In the process method, upon each received record, split the value string into words, and update their counts into the state store (we will talk about this feature later in the section).
  • In the punctuate method, iterate the local state store and send the aggregated counts to the downstream processor, and commit the current stream state.

Processor Topology

With the customized processors defined in the Processor API, developers can use the TopologyBuilder to build a processor topology by connecting these processors together:

    TopologyBuilder builder = new TopologyBuilder();

    builder.addSource("SOURCE", "src-topic")

        .addProcessor("PROCESS1", MyProcessor1::new /* the ProcessorSupplier that can generate MyProcessor1 */, "SOURCE")
        .addProcessor("PROCESS2", MyProcessor2::new /* the ProcessorSupplier that can generate MyProcessor2 */, "PROCESS1")
        .addProcessor("PROCESS3", MyProcessor3::new /* the ProcessorSupplier that can generate MyProcessor3 */, "PROCESS1")

        .addSink("SINK1", "sink-topic1", "PROCESS1")
        .addSink("SINK2", "sink-topic2", "PROCESS2")
        .addSink("SINK3", "sink-topic3", "PROCESS3");
There are several steps in the above code to build the topology, and here is a quick walk through:
  • First of all a source node named "SOURCE" is added to the topology using the addSource method, with one Kafka topic "src-topic" fed to it.
  • Three processor nodes are then added using the addProcessor method; here the first processor is a child of the "SOURCE" node, but is the parent of the other two processors.
  • Finally three sink nodes are added to complete the topology using the addSink method, each piping from a different parent processor node and writing to a separate topic.

Local State Store

Note that the Processor API is not limited to only accessing the current records as they arrive, but can also maintain local state stores that keep recently arrived records to use in stateful processing operations such as aggregation or windowed joins. To take advantage of this local states, developers can use the TopologyBuilder.addStateStore method when building the processor topology to create the local state and associate it with the processor nodes that needs to access it; or they can connect a created local state store with the existing processor nodes through TopologyBuilder.connectProcessorAndStateStores.

    TopologyBuilder builder = new TopologyBuilder();

    builder.addSource("SOURCE", "src-topic")

        .addProcessor("PROCESS1", MyProcessor1::new, "SOURCE")
        // create the in-memory state store "COUNTS" associated with processor "PROCESS1"
        .addStateStore(Stores.create("COUNTS").withStringKeys().withStringValues().inMemory().build(), "PROCESS1")
        .addProcessor("PROCESS2", MyProcessor3::new /* the ProcessorSupplier that can generate MyProcessor3 */, "PROCESS1")
        .addProcessor("PROCESS3", MyProcessor3::new /* the ProcessorSupplier that can generate MyProcessor3 */, "PROCESS1")

        // connect the state store "COUNTS" with processor "PROCESS2"
        .connectProcessorAndStateStores("PROCESS2", "COUNTS");

        .addSink("SINK1", "sink-topic1", "PROCESS1")
        .addSink("SINK2", "sink-topic2", "PROCESS2")
        .addSink("SINK3", "sink-topic3", "PROCESS3");

In the next section we present another way to build the processor topology: the Kafka Streams DSL.

高レベルストリームDSL

To build a processor topology using the Streams DSL, developers can apply the KStreamBuilder class, which is extended from the TopologyBuilder. A simple example is included with the source code for Kafka in the streams/examples package. The rest of this section will walk through some code to demonstrate the key steps in creating a topology using the Streams DSL, but we recommend developers to read the full example source codes for details.
Create Source Streams from Kafka

Either a record stream (defined as KStream) or a changelog stream (defined as KTable) can be created as a source stream from one or more Kafka topics (for KTable you can only create the source stream from a single topic).

    KStreamBuilder builder = new KStreamBuilder();

    KStream source1 = builder.stream("topic1", "topic2");
    KTable source2 = builder.table("topic3");
Transform a stream

There is a list of transformation operations provided for KStream and KTable respectively. Each of these operations may generate either one or more KStream and KTable objects and can be translated into one or more connected processors into the underlying processor topology. All these transformation methods can be chained together to compose a complex processor topology. Since KStream and KTable are strongly typed, all these transformation operations are defined as generics functions where users could specify the input and output data types.

Among these transformations, filter, map, mapValues, etc, are stateless transformation operations and can be applied to both KStream and KTable, where users can usually pass a customized function to these functions as a parameter, such as Predicate for filter, KeyValueMapper for map, etc:

    // written in Java 8+, using lambda expressions
    KStream mapped = source1.mapValue(record -> record.get("category"));

Stateless transformations, by definition, do not depend on any state for processing, and hence implementation-wise they do not require a state store associated with the stream processor; Stateful transformations, on the other hand, require accessing an associated state for processing and producing outputs. For example, in join and aggregate operations, a windowing state is usually used to store all the received records within the defined window boundary so far. The operators can then access these accumulated records in the store and compute based on them.

    // written in Java 8+, using lambda expressions
    KTable, Long> counts = source1.aggregateByKey(
        () -> 0L,  // initial value
        (aggKey, value, aggregate) -> aggregate + 1L,   // aggregating value
        HoppingWindows.of("counts").with(5000L).every(1000L), // intervals in milliseconds
    );

    KStream joined = source1.leftJoin(source2,
        (record1, record2) -> record1.get("user") + "-" + record2.get("region");
    );
Write streams back to Kafka

At the end of the processing, users can choose to (continuously) write the final resulted streams back to a Kafka topic through KStream.to and KTable.to.

    joined.to("topic4");
If your application needs to continue reading and processing the records after they have been materialized to a topic via to above, one option is to construct a new stream that reads from the output topic; Kafka Streams provides a convenience method called through:
    // equivalent to
    //
    // joined.to("topic4");
    // materialized = builder.stream("topic4");
    KStream materialized = joined.through("topic4");

Besides defining the topology, developers will also need to configure their applications in StreamsConfig before running it. A complete list of Kafka Streams configs can be found here.

TOP
inserted by FC2 system