You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by gu...@apache.org on 2016/12/14 01:59:53 UTC

[1/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Repository: kafka
Updated Branches:
  refs/heads/trunk 448f194c7 -> 53428694a


http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/streams.html
----------------------------------------------------------------------
diff --git a/docs/streams.html b/docs/streams.html
index 306b2a5..dec17ef 100644
--- a/docs/streams.html
+++ b/docs/streams.html
@@ -15,367 +15,410 @@
   ~ limitations under the License.
   ~-->
 
-<h3><a id="streams_overview" href="#streams_overview">9.1 Overview</a></h3>
-
-<p>
-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 <b>low barrier to entry</b>: 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.
-</p>
-<p>
-Some highlights of Kafka Streams:
-</p>
-
-<ul>
-    <li>Designed as a <b>simple and lightweight client library</b>, 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.</li>
-    <li>Has <b>no external dependencies on systems other than Apache Kafka itself</b> as the internal messaging layer; notably, it uses Kafka's partitioning model to horizontally scale processing while maintaining strong ordering guarantees.</li>
-    <li>Supports <b>fault-tolerant local state</b>, which enables very fast and efficient stateful operations like joins and windowed aggregations.</li>
-    <li>Employs <b>one-record-at-a-time processing</b> to achieve low processing latency, and supports <b>event-time based windowing operations</b>.</li>
-    <li>Offers necessary stream processing primitives, along with a <b>high-level Streams DSL</b> and a <b>low-level Processor API</b>.</li>
-
-</ul>
-
-<h3><a id="streams_developer" href="#streams_developer">9.2 Developer Guide</a></h3>
-
-<p>
-There is a <a href="#quickstart_kafkastreams">quickstart</a> 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.
-</p>
-
-<h4><a id="streams_concepts" href="#streams_concepts">Core Concepts</a></h4>
-
-<p>
-We first summarize the key concepts of Kafka Streams.
-</p>
-
-<h5><a id="streams_topology" href="#streams_topology">Stream Processing Topology</a></h5>
-
-<ul>
-    <li>A <b>stream</b> is 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 <b>data record</b> is defined as a key-value pair.</li>
-    <li>A <b>stream processing application</b> written in Kafka Streams defines its computational logic through one or more <b>processor topologies</b>, where a processor topology is a graph of stream processors (nodes) that are connected by streams (edges).</li>
-    <li>A <b>stream processor</b> 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.</li>
-</ul>
-
-<p>
-Kafka Streams offers two ways to define the stream processing topology: the <a href="#streams_dsl"><b>Kafka Streams DSL</b></a> provides
-the most common data transformation operations such as <code>map</code> and <code>filter</code>; the lower-level <a href="#streams_processor"><b>Processor API</b></a> allows
-developers define and connect custom processors as well as to interact with <a href="#streams_state">state stores</a>.
-</p>
-
-<h5><a id="streams_time" href="#streams_time">Time</a></h5>
-
-<p>
-A critical aspect in stream processing is the notion of <b>time</b>, and how it is modeled and integrated.
-For example, some operations such as <b>windowing</b> are defined based on time boundaries.
-</p>
-<p>
-Common notions of time in streams are:
-</p>
-
-<ul>
-    <li><b>Event time</b> - The point in time when an event or data record occurred, i.e. was originally created "at the source".</li>
-    <li><b>Processing time</b> - 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.</li>
-    <li><b>Ingestion time</b> - The point in time when an event or data record is stored in a topic partition by a Kafka broker. The difference to event time is that this ingestion timestamp is generated when the record is appended to the target topic by the Kafka broker, not when the record is created "at the source". The difference to processing time is that processing time is when the stream processing application processes the record. For example, if a record is never processed, there is no notion of processing time for it, but it still has an ingestion time.
-</ul>
-<p>
-The choice between event-time and ingestion-time is actually done through the configuration of Kafka (not Kafka Streams): From Kafka 0.10.x onwards, timestamps are automatically embedded into Kafka messages. Depending on Kafka's configuration these timestamps represent event-time or ingestion-time. The respective Kafka configuration setting can be specified on the broker level or per topic. The default timestamp extractor in Kafka Streams will retrieve these embedded timestamps as-is. Hence, the effective time semantics of your application depend on the effective Kafka configuration for these embedded timestamps.
-</p>
-<p>
-Kafka Streams assigns a <b>timestamp</b> to every data record
-via the <code>TimestampExtractor</code> 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.
-</p>
-
-<p>
-  Finally, whenever a Kafka Streams application writes records to Kafka, then it will also assign timestamps to these new records. The way the timestamps are assigned depends on the context:
-  <ul>
-    <li> When new output records are generated via processing some input record, for example, <code>context.forward()</code> triggered in the <code>process()</code> function call, output record timestamps are inherited from input record timestamps directly.</li>
-    <li> When new output records are generated via periodic functions such as <code>punctuate()</code>, the output record timestamp is defined as the current internal time (obtained through <code>context.timestamp()</code>) of the stream task.</li>
-    <li> For aggregations, the timestamp of a resulting aggregate update record will be that of the latest arrived input record that triggered the update.</li>
-  </ul>
-</p>
-
-<h5><a id="streams_state" href="#streams_state">States</a></h5>
-
-<p>
-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 <a href="#streams_dsl"><b>Kafka Streams DSL</b></a>.
-</p>
-<p>
-Kafka Streams provides so-called <b>state stores</b>, 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.
-</p>
-<p>
-  Kafka Streams allows direct read-only queries of the state stores by methods, threads, processes or applications external to the stream processing application that created the state stores. This is provided through a feature called <b>Interactive Queries</b>. All stores are named and Interactive Queries exposes only the read operations of the underlying implementation. 
-</p>
-<br>
-<p>
-As we have mentioned above, the computational logic of a Kafka Streams application is defined as a <a href="#streams_topology">processor topology</a>.
-Currently Kafka Streams provides two sets of APIs to define the processor topology, which will be described in the subsequent sections.
-</p>
-
-<h4><a id="streams_processor" href="#streams_processor">Low-Level Processor API</a></h4>
-
-<h5><a id="streams_processor_process" href="#streams_processor_process">Processor</a></h5>
-
-<p>
-Developers can define their customized processing logic by implementing the <code>Processor</code> interface, which
-provides <code>process</code> and <code>punctuate</code> methods. The <code>process</code> method is performed on each
-of the received record; and the <code>punctuate</code> method is performed periodically based on elapsed time.
-In addition, the processor can maintain the current <code>ProcessorContext</code> instance variable initialized in the
-<code>init</code> method, and use the context to schedule the punctuation period (<code>context().schedule</code>), to
-forward the modified / new key-value pair to downstream processors (<code>context().forward</code>), to commit the current
-processing progress (<code>context().commit</code>), etc.
-</p>
-
-<pre>
-    public class MyProcessor extends Processor<String, String> {
-        private ProcessorContext context;
-        private KeyValueStore<String, Integer> kvStore;
-
-        @Override
-        @SuppressWarnings("unchecked")
-        public void init(ProcessorContext context) {
-            this.context = context;
-            this.context.schedule(1000);
-            this.kvStore = (KeyValueStore<String, Integer>) 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);
+<script><!--#include virtual="js/templateData.js" --></script>
+
+<script id="streams-template" type="text/x-handlebars-template">
+    <h1>Streams</h1>
+
+        <ol class="toc">
+            <li>
+                <a href="#streams_overview">Overview</a>
+            </li>
+            <li>
+                <a href="#streams_developer">Developer guide</a>
+                <ul>
+                    <li><a href="#streams_concepts">Core concepts</a>
+                    <li><a href="#streams_processor">Low-level processor API</a>
+                    <li><a href="#streams_dsl">High-level streams DSL</a>
+                </ul>
+            </li>
+        </ol>
+
+        <h2><a id="streams_overview" href="#overview">Overview</a></h2>
+
+        <p>
+        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 <b>low barrier to entry</b>: 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.
+        </p>
+        <p>
+        Some highlights of Kafka Streams:
+        </p>
+
+        <ul>
+            <li>Designed as a <b>simple and lightweight client library</b>, 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.</li>
+            <li>Has <b>no external dependencies on systems other than Apache Kafka itself</b> as the internal messaging layer; notably, it uses Kafka's partitioning model to horizontally scale processing while maintaining strong ordering guarantees.</li>
+            <li>Supports <b>fault-tolerant local state</b>, which enables very fast and efficient stateful operations like joins and windowed aggregations.</li>
+            <li>Employs <b>one-record-at-a-time processing</b> to achieve low processing latency, and supports <b>event-time based windowing operations</b>.</li>
+            <li>Offers necessary stream processing primitives, along with a <b>high-level Streams DSL</b> and a <b>low-level Processor API</b>.</li>
+
+        </ul>
+
+        <h2><a id="streams_developer" href="#streams_developer">Developer Guide</a></h2>
+
+        <p>
+        There is a <a href="#quickstart_kafkastreams">quickstart</a> 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.
+        </p>
+
+        <h4><a id="streams_concepts" href="#streams_concepts">Core Concepts</a></h4>
+
+        <p>
+        We first summarize the key concepts of Kafka Streams.
+        </p>
+
+        <h5><a id="streams_topology" href="#streams_topology">Stream Processing Topology</a></h5>
+
+        <ul>
+            <li>A <b>stream</b> is 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 <b>data record</b> is defined as a key-value pair.</li>
+            <li>A <b>stream processing application</b> written in Kafka Streams defines its computational logic through one or more <b>processor topologies</b>, where a processor topology is a graph of stream processors (nodes) that are connected by streams (edges).</li>
+            <li>A <b>stream processor</b> 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.</li>
+        </ul>
+
+        <p>
+        Kafka Streams offers two ways to define the stream processing topology: the <a href="#streams_dsl"><b>Kafka Streams DSL</b></a> provides
+        the most common data transformation operations such as <code>map</code> and <code>filter</code>; the lower-level <a href="#streams_processor"><b>Processor API</b></a> allows
+        developers define and connect custom processors as well as to interact with <a href="#streams_state">state stores</a>.
+        </p>
+
+        <h5><a id="streams_time" href="#streams_time">Time</a></h5>
+
+        <p>
+        A critical aspect in stream processing is the notion of <b>time</b>, and how it is modeled and integrated.
+        For example, some operations such as <b>windowing</b> are defined based on time boundaries.
+        </p>
+        <p>
+        Common notions of time in streams are:
+        </p>
+
+        <ul>
+            <li><b>Event time</b> - The point in time when an event or data record occurred, i.e. was originally created "at the source".</li>
+            <li><b>Processing time</b> - 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.</li>
+            <li><b>Ingestion time</b> - The point in time when an event or data record is stored in a topic partition by a Kafka broker. The difference to event time is that this ingestion timestamp is generated when the record is appended to the target topic by the Kafka broker, not when the record is created "at the source". The difference to processing time is that processing time is when the stream processing application processes the record. For example, if a record is never processed, there is no notion of processing time for it, but it still has an ingestion time.
+        </ul>
+        <p>
+        The choice between event-time and ingestion-time is actually done through the configuration of Kafka (not Kafka Streams): From Kafka 0.10.x onwards, timestamps are automatically embedded into Kafka messages. Depending on Kafka's configuration these timestamps represent event-time or ingestion-time. The respective Kafka configuration setting can be specified on the broker level or per topic. The default timestamp extractor in Kafka Streams will retrieve these embedded timestamps as-is. Hence, the effective time semantics of your application depend on the effective Kafka configuration for these embedded timestamps.
+        </p>
+        <p>
+        Kafka Streams assigns a <b>timestamp</b> to every data record
+        via the <code>TimestampExtractor</code> 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.
+        </p>
+
+        <p>
+        Finally, whenever a Kafka Streams application writes records to Kafka, then it will also assign timestamps to these new records. The way the timestamps are assigned depends on the context:
+        <ul>
+            <li> When new output records are generated via processing some input record, for example, <code>context.forward()</code> triggered in the <code>process()</code> function call, output record timestamps are inherited from input record timestamps directly.</li>
+            <li> When new output records are generated via periodic functions such as <code>punctuate()</code>, the output record timestamp is defined as the current internal time (obtained through <code>context.timestamp()</code>) of the stream task.</li>
+            <li> For aggregations, the timestamp of a resulting aggregate update record will be that of the latest arrived input record that triggered the update.</li>
+        </ul>
+        </p>
+
+        <h5><a id="streams_state" href="#streams_state">States</a></h5>
+
+        <p>
+        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 <a href="#streams_dsl"><b>Kafka Streams DSL</b></a>.
+        </p>
+        <p>
+        Kafka Streams provides so-called <b>state stores</b>, 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.
+        </p>
+        <p>
+        Kafka Streams allows direct read-only queries of the state stores by methods, threads, processes or applications external to the stream processing application that created the state stores. This is provided through a feature called <b>Interactive Queries</b>. All stores are named and Interactive Queries exposes only the read operations of the underlying implementation. 
+        </p>
+        <br>
+        <p>
+        As we have mentioned above, the computational logic of a Kafka Streams application is defined as a <a href="#streams_topology">processor topology</a>.
+        Currently Kafka Streams provides two sets of APIs to define the processor topology, which will be described in the subsequent sections.
+        </p>
+
+        <h4><a id="streams_processor" href="#streams_processor">Low-Level Processor API</a></h4>
+
+        <h5><a id="streams_processor_process" href="#streams_processor_process">Processor</a></h5>
+
+        <p>
+        Developers can define their customized processing logic by implementing the <code>Processor</code> interface, which
+        provides <code>process</code> and <code>punctuate</code> methods. The <code>process</code> method is performed on each
+        of the received record; and the <code>punctuate</code> method is performed periodically based on elapsed time.
+        In addition, the processor can maintain the current <code>ProcessorContext</code> instance variable initialized in the
+        <code>init</code> method, and use the context to schedule the punctuation period (<code>context().schedule</code>), to
+        forward the modified / new key-value pair to downstream processors (<code>context().forward</code>), to commit the current
+        processing progress (<code>context().commit</code>), etc.
+        </p>
+
+        <pre>
+            public class MyProcessor extends Processor<String, String> {
+                private ProcessorContext context;
+                private KeyValueStore<String, Integer> kvStore;
+
+                @Override
+                @SuppressWarnings("unchecked")
+                public void init(ProcessorContext context) {
+                    this.context = context;
+                    this.context.schedule(1000);
+                    this.kvStore = (KeyValueStore<String, Integer>) context.getStateStore("Counts");
                 }
-            }
-        }
 
-        @Override
-        public void punctuate(long timestamp) {
-            KeyValueIterator<String, Integer> iter = this.kvStore.all();
+                @Override
+                public void process(String dummy, String line) {
+                    String[] words = line.toLowerCase().split(" ");
 
-            while (iter.hasNext()) {
-                KeyValue<String, Integer> entry = iter.next();
-                context.forward(entry.key, entry.value.toString());
-            }
+                    for (String word : words) {
+                        Integer oldValue = this.kvStore.get(word);
 
-            iter.close();
-            context.commit();
-        }
+                        if (oldValue == null) {
+                            this.kvStore.put(word, 1);
+                        } else {
+                            this.kvStore.put(word, oldValue + 1);
+                        }
+                    }
+                }
+
+                @Override
+                public void punctuate(long timestamp) {
+                    KeyValueIterator<String, Integer> iter = this.kvStore.all();
+
+                    while (iter.hasNext()) {
+                        KeyValue<String, Integer> entry = iter.next();
+                        context.forward(entry.key, entry.value.toString());
+                    }
 
-        @Override
-        public void close() {
-            this.kvStore.close();
-        }
-    };
-</pre>
+                    iter.close();
+                    context.commit();
+                }
+
+                @Override
+                public void close() {
+                    this.kvStore.close();
+                }
+            };
+        </pre>
 
-<p>
-In the above implementation, the following actions are performed:
+        <p>
+        In the above implementation, the following actions are performed:
 
-<ul>
-    <li>In the <code>init</code> method, schedule the punctuation every 1 second and retrieve the local state store by its name "Counts".</li>
-    <li>In the <code>process</code> 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).</li>
-    <li>In the <code>punctuate</code> method, iterate the local state store and send the aggregated counts to the downstream processor, and commit the current stream state.</li>
-</ul>
-</p>
+        <ul>
+            <li>In the <code>init</code> method, schedule the punctuation every 1 second and retrieve the local state store by its name "Counts".</li>
+            <li>In the <code>process</code> 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).</li>
+            <li>In the <code>punctuate</code> method, iterate the local state store and send the aggregated counts to the downstream processor, and commit the current stream state.</li>
+        </ul>
+        </p>
 
-<h5><a id="streams_processor_topology" href="#streams_processor_topology">Processor Topology</a></h5>
+        <h5><a id="streams_processor_topology" href="#streams_processor_topology">Processor Topology</a></h5>
 
-<p>
-With the customized processors defined in the Processor API, developers can use the <code>TopologyBuilder</code> to build a processor topology
-by connecting these processors together:
+        <p>
+        With the customized processors defined in the Processor API, developers can use the <code>TopologyBuilder</code> to build a processor topology
+        by connecting these processors together:
 
-<pre>
-    TopologyBuilder builder = new TopologyBuilder();
+        <pre>
+            TopologyBuilder builder = new TopologyBuilder();
 
-    builder.addSource("SOURCE", "src-topic")
+            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")
+                .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");
-</pre>
+                .addSink("SINK1", "sink-topic1", "PROCESS1")
+                .addSink("SINK2", "sink-topic2", "PROCESS2")
+                .addSink("SINK3", "sink-topic3", "PROCESS3");
+        </pre>
 
-There are several steps in the above code to build the topology, and here is a quick walk through:
+        There are several steps in the above code to build the topology, and here is a quick walk through:
 
-<ul>
-    <li>First of all a source node named "SOURCE" is added to the topology using the <code>addSource</code> method, with one Kafka topic "src-topic" fed to it.</li>
-    <li>Three processor nodes are then added using the <code>addProcessor</code> method; here the first processor is a child of the "SOURCE" node, but is the parent of the other two processors.</li>
-    <li>Finally three sink nodes are added to complete the topology using the <code>addSink</code> method, each piping from a different parent processor node and writing to a separate topic.</li>
-</ul>
-</p>
+        <ul>
+            <li>First of all a source node named "SOURCE" is added to the topology using the <code>addSource</code> method, with one Kafka topic "src-topic" fed to it.</li>
+            <li>Three processor nodes are then added using the <code>addProcessor</code> method; here the first processor is a child of the "SOURCE" node, but is the parent of the other two processors.</li>
+            <li>Finally three sink nodes are added to complete the topology using the <code>addSink</code> method, each piping from a different parent processor node and writing to a separate topic.</li>
+        </ul>
+        </p>
 
-<h5><a id="streams_processor_statestore" href="#streams_processor_statestore">Local State Store</a></h5>
+        <h5><a id="streams_processor_statestore" href="#streams_processor_statestore">Local State Store</a></h5>
 
-<p>
-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 <code>TopologyBuilder.addStateStore</code> 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 <code>TopologyBuilder.connectProcessorAndStateStores</code>.
-
-<pre>
-    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");
-</pre>
-
-</p>
-
-In the next section we present another way to build the processor topology: the Kafka Streams DSL.
-
-<h4><a id="streams_dsl" href="#streams_dsl">High-Level Streams DSL</a></h4>
-
-To build a processor topology using the Streams DSL, developers can apply the <code>KStreamBuilder</code> class, which is extended from the <code>TopologyBuilder</code>.
-A simple example is included with the source code for Kafka in the <code>streams/examples</code> 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. 
-
-<h5><a id="streams_kstream_ktable" href="#streams_kstream_ktable">KStream and KTable</a></h5>
-The DSL uses two main abstractions. A <b>KStream</b> is an abstraction of a record stream, where each data record represents a self-contained datum in the unbounded data set. A <b>KTable</b> is an abstraction of a changelog stream, where each data record represents an update. More precisely, the value in a data record is considered to be an update of the last value for the same record key, if any (if a corresponding key doesn't exist yet, the update will be considered a create). To illustrate the difference between KStreams and KTables, let\u2019s imagine the following two data records are being sent to the stream: <code>("alice", 1) --> ("alice", 3)</code>. If these records a KStream and the stream processing application were to sum the values it would return <code>4</code>. If these records were a KTable, the return would be <code>3</code>, since the last record would be considered as an update.
-
-
-
-<h5><a id="streams_dsl_source" href="#streams_dsl_source">Create Source Streams from Kafka</a></h5>
-
-<p>
-Either a <b>record stream</b> (defined as <code>KStream</code>) or a <b>changelog stream</b> (defined as <code>KTable</code>)
-can be created as a source stream from one or more Kafka topics (for <code>KTable</code> you can only create the source stream
-from a single topic).
-</p>
-
-<pre>
-    KStreamBuilder builder = new KStreamBuilder();
-
-    KStream&lt;String, GenericRecord&gt; source1 = builder.stream("topic1", "topic2");
-    KTable&lt;String, GenericRecord&gt; source2 = builder.table("topic3", "stateStoreName");
-</pre>
-
-<h5><a id="streams_dsl_windowing" href="#streams_dsl_windowing">Windowing a stream</a></h5>
-A stream processor may need to divide data records into time buckets, i.e. to <b>window</b> the stream by time. This is usually needed for join and aggregation operations, etc. Kafka Streams currently defines the following types of windows:
-<ul>
-  <li><b>Hopping time windows</b> are windows based on time intervals. They model fixed-sized, (possibly) overlapping windows. A hopping window is defined by two properties: the window's size and its advance interval (aka "hop"). The advance interval specifies by how much a window moves forward relative to the previous one. For example, you can configure a hopping window with a size 5 minutes and an advance interval of 1 minute. Since hopping windows can overlap a data record may belong to more than one such windows.</li>
-  <li><b>Tumbling time windows</b> are a special case of hopping time windows and, like the latter, are windows based on time intervals. They model fixed-size, non-overlapping, gap-less windows. A tumbling window is defined by a single property: the window's size. A tumbling window is a hopping window whose window size is equal to its advance interval. Since tumbling windows never overlap, a data record will belong to one and only one window.</li>
-  <li><b>Sliding windows</b> model a fixed-size window that slides continuously over the time axis; here, two data records are said to be included in the same window if the difference of their timestamps is within the window size. Thus, sliding windows are not aligned to the epoch, but on the data record timestamps. In Kafka Streams, sliding windows are used only for join operations, and can be specified through the <code>JoinWindows</code> class.</li>
-  </ul>
-
-<h5><a id="streams_dsl_joins" href="#streams_dsl_joins">Joins</a></h5>
-A <b>join</b> operation merges two streams based on the keys of their data records, and yields a new stream. A join over record streams usually needs to be performed on a windowing basis because otherwise the number of records that must be maintained for performing the join may grow indefinitely. In Kafka Streams, you may perform the following join operations:
-<ul>
-  <li><b>KStream-to-KStream Joins</b> are always windowed joins, since otherwise the memory and state required to compute the join would grow infinitely in size. Here, a newly received record from one of the streams is joined with the other stream's records within the specified window interval to produce one result for each matching pair based on user-provided <code>ValueJoiner</code>. A new <code>KStream</code> instance representing the result stream of the join is returned from this operator.</li>
-  
-  <li><b>KTable-to-KTable Joins</b> are join operations designed to be consistent with the ones in relational databases. Here, both changelog streams are materialized into local state stores first. When a new record is received from one of the streams, it is joined with the other stream's materialized state stores to produce one result for each matching pair based on user-provided ValueJoiner. A new <code>KTable</code> instance representing the result stream of the join, which is also a changelog stream of the represented table, is returned from this operator.</li>
-  <li><b>KStream-to-KTable Joins</b> allow you to perform table lookups against a changelog stream (<code>KTable</code>) upon receiving a new record from another record stream (KStream). An example use case would be to enrich a stream of user activities (<code>KStream</code>) with the latest user profile information (<code>KTable</code>). Only records received from the record stream will trigger the join and produce results via <code>ValueJoiner</code>, not vice versa (i.e., records received from the changelog stream will be used only to update the materialized state store). A new <code>KStream</code> instance representing the result stream of the join is returned from this operator.</li>
-  </ul>
-
-Depending on the operands the following join operations are supported: <b>inner joins</b>, <b>outer joins</b> and <b>left joins</b>. Their semantics are similar to the corresponding operators in relational databases.
-
-<h5><a id="streams_dsl_transform" href="#streams_dsl_transform">Transform a stream</a></h5>
-
-<p>
-There is a list of transformation operations provided for <code>KStream</code> and <code>KTable</code> respectively.
-Each of these operations may generate either one or more <code>KStream</code> and <code>KTable</code> 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 <code>KStream</code> and <code>KTable</code> are strongly typed, all these transformation operations are defined as
-generics functions where users could specify the input and output data types.
-</p>
-
-<p>
-Among these transformations, <code>filter</code>, <code>map</code>, <code>mapValues</code>, etc, are stateless
-transformation operations and can be applied to both <code>KStream</code> and <code>KTable</code>,
-where users can usually pass a customized function to these functions as a parameter, such as <code>Predicate</code> for <code>filter</code>,
-<code>KeyValueMapper</code> for <code>map</code>, etc:
-
-</p>
-
-<pre>
-    // written in Java 8+, using lambda expressions
-    KStream&lt;String, GenericRecord&gt; mapped = source1.mapValue(record -> record.get("category"));
-</pre>
-
-<p>
-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 <code>join</code> and <code>aggregate</code> 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.
-</p>
-
-<pre>
-    // written in Java 8+, using lambda expressions
-    KTable&lt;Windowed&lt;String&gt;, Long&gt; counts = source1.groupByKey().aggregate(
-        () -> 0L,  // initial value
-        (aggKey, value, aggregate) -> aggregate + 1L,   // aggregating value
-        TimeWindows.of("counts", 5000L).advanceBy(1000L), // intervals in milliseconds
-        Serdes.Long() // serde for aggregated value
-    );
-
-    KStream&lt;String, String&gt; joined = source1.leftJoin(source2,
-        (record1, record2) -> record1.get("user") + "-" + record2.get("region");
-    );
-</pre>
-
-<h5><a id="streams_dsl_sink" href="#streams_dsl_sink">Write streams back to Kafka</a></h5>
-
-<p>
-At the end of the processing, users can choose to (continuously) write the final resulted streams back to a Kafka topic through
-<code>KStream.to</code> and <code>KTable.to</code>.
-</p>
-
-<pre>
-    joined.to("topic4");
-</pre>
-
-If your application needs to continue reading and processing the records after they have been materialized
-to a topic via <code>to</code> above, one option is to construct a new stream that reads from the output topic;
-Kafka Streams provides a convenience method called <code>through</code>:
-
-<pre>
-    // equivalent to
-    //
-    // joined.to("topic4");
-    // materialized = builder.stream("topic4");
-    KStream&lt;String, String&gt; materialized = joined.through("topic4");
-</pre>
-
-
-<br>
-<p>
-Besides defining the topology, developers will also need to configure their applications
-in <code>StreamsConfig</code> before running it. A complete list of
-Kafka Streams configs can be found <a href="#streamsconfigs"><b>here</b></a>.
-</p>
+        <p>
+        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 <code>TopologyBuilder.addStateStore</code> 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 <code>TopologyBuilder.connectProcessorAndStateStores</code>.
+
+        <pre>
+            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");
+        </pre>
+
+        </p>
+
+        In the next section we present another way to build the processor topology: the Kafka Streams DSL.
+
+        <h4><a id="streams_dsl" href="#streams_dsl">High-Level Streams DSL</a></h4>
+
+        To build a processor topology using the Streams DSL, developers can apply the <code>KStreamBuilder</code> class, which is extended from the <code>TopologyBuilder</code>.
+        A simple example is included with the source code for Kafka in the <code>streams/examples</code> 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. 
+
+        <h5><a id="streams_kstream_ktable" href="#streams_kstream_ktable">KStream and KTable</a></h5>
+        The DSL uses two main abstractions. A <b>KStream</b> is an abstraction of a record stream, where each data record represents a self-contained datum in the unbounded data set. A <b>KTable</b> is an abstraction of a changelog stream, where each data record represents an update. More precisely, the value in a data record is considered to be an update of the last value for the same record key, if any (if a corresponding key doesn't exist yet, the update will be considered a create). To illustrate the difference between KStreams and KTables, let\u2019s imagine the following two data records are being sent to the stream: <code>("alice", 1) --> ("alice", 3)</code>. If these records a KStream and the stream processing application were to sum the values it would return <code>4</code>. If these records were a KTable, the return would be <code>3</code>, since the last record would be considered as an update.
+
+
+
+        <h5><a id="streams_dsl_source" href="#streams_dsl_source">Create Source Streams from Kafka</a></h5>
+
+        <p>
+        Either a <b>record stream</b> (defined as <code>KStream</code>) or a <b>changelog stream</b> (defined as <code>KTable</code>)
+        can be created as a source stream from one or more Kafka topics (for <code>KTable</code> you can only create the source stream
+        from a single topic).
+        </p>
+
+        <pre>
+            KStreamBuilder builder = new KStreamBuilder();
+
+            KStream<String, GenericRecord> source1 = builder.stream("topic1", "topic2");
+            KTable<String, GenericRecord> source2 = builder.table("topic3", "stateStoreName");
+        </pre>
+
+        <h5><a id="streams_dsl_windowing" href="#streams_dsl_windowing">Windowing a stream</a></h5>
+        A stream processor may need to divide data records into time buckets, i.e. to <b>window</b> the stream by time. This is usually needed for join and aggregation operations, etc. Kafka Streams currently defines the following types of windows:
+        <ul>
+        <li><b>Hopping time windows</b> are windows based on time intervals. They model fixed-sized, (possibly) overlapping windows. A hopping window is defined by two properties: the window's size and its advance interval (aka "hop"). The advance interval specifies by how much a window moves forward relative to the previous one. For example, you can configure a hopping window with a size 5 minutes and an advance interval of 1 minute. Since hopping windows can overlap a data record may belong to more than one such windows.</li>
+        <li><b>Tumbling time windows</b> are a special case of hopping time windows and, like the latter, are windows based on time intervals. They model fixed-size, non-overlapping, gap-less windows. A tumbling window is defined by a single property: the window's size. A tumbling window is a hopping window whose window size is equal to its advance interval. Since tumbling windows never overlap, a data record will belong to one and only one window.</li>
+        <li><b>Sliding windows</b> model a fixed-size window that slides continuously over the time axis; here, two data records are said to be included in the same window if the difference of their timestamps is within the window size. Thus, sliding windows are not aligned to the epoch, but on the data record timestamps. In Kafka Streams, sliding windows are used only for join operations, and can be specified through the <code>JoinWindows</code> class.</li>
+        </ul>
+
+        <h5><a id="streams_dsl_joins" href="#streams_dsl_joins">Joins</a></h5>
+        A <b>join</b> operation merges two streams based on the keys of their data records, and yields a new stream. A join over record streams usually needs to be performed on a windowing basis because otherwise the number of records that must be maintained for performing the join may grow indefinitely. In Kafka Streams, you may perform the following join operations:
+        <ul>
+        <li><b>KStream-to-KStream Joins</b> are always windowed joins, since otherwise the memory and state required to compute the join would grow infinitely in size. Here, a newly received record from one of the streams is joined with the other stream's records within the specified window interval to produce one result for each matching pair based on user-provided <code>ValueJoiner</code>. A new <code>KStream</code> instance representing the result stream of the join is returned from this operator.</li>
+        
+        <li><b>KTable-to-KTable Joins</b> are join operations designed to be consistent with the ones in relational databases. Here, both changelog streams are materialized into local state stores first. When a new record is received from one of the streams, it is joined with the other stream's materialized state stores to produce one result for each matching pair based on user-provided ValueJoiner. A new <code>KTable</code> instance representing the result stream of the join, which is also a changelog stream of the represented table, is returned from this operator.</li>
+        <li><b>KStream-to-KTable Joins</b> allow you to perform table lookups against a changelog stream (<code>KTable</code>) upon receiving a new record from another record stream (KStream). An example use case would be to enrich a stream of user activities (<code>KStream</code>) with the latest user profile information (<code>KTable</code>). Only records received from the record stream will trigger the join and produce results via <code>ValueJoiner</code>, not vice versa (i.e., records received from the changelog stream will be used only to update the materialized state store). A new <code>KStream</code> instance representing the result stream of the join is returned from this operator.</li>
+        </ul>
+
+        Depending on the operands the following join operations are supported: <b>inner joins</b>, <b>outer joins</b> and <b>left joins</b>. Their semantics are similar to the corresponding operators in relational databases.
+        a
+        <h5><a id="streams_dsl_transform" href="#streams_dsl_transform">Transform a stream</a></h5>
+
+        <p>
+        There is a list of transformation operations provided for <code>KStream</code> and <code>KTable</code> respectively.
+        Each of these operations may generate either one or more <code>KStream</code> and <code>KTable</code> 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 <code>KStream</code> and <code>KTable</code> are strongly typed, all these transformation operations are defined as
+        generics functions where users could specify the input and output data types.
+        </p>
+
+        <p>
+        Among these transformations, <code>filter</code>, <code>map</code>, <code>mapValues</code>, etc, are stateless
+        transformation operations and can be applied to both <code>KStream</code> and <code>KTable</code>,
+        where users can usually pass a customized function to these functions as a parameter, such as <code>Predicate</code> for <code>filter</code>,
+        <code>KeyValueMapper</code> for <code>map</code>, etc:
+
+        </p>
+
+        <pre>
+            // written in Java 8+, using lambda expressions
+            KStream<String, GenericRecord> mapped = source1.mapValue(record -> record.get("category"));
+        </pre>
+
+        <p>
+        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 <code>join</code> and <code>aggregate</code> 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.
+        </p>
+
+        <pre>
+            // written in Java 8+, using lambda expressions
+            KTable<Windowed<String>, Long> counts = source1.groupByKey().aggregate(
+                () -> 0L,  // initial value
+                (aggKey, value, aggregate) -> aggregate + 1L,   // aggregating value
+                TimeWindows.of("counts", 5000L).advanceBy(1000L), // intervals in milliseconds
+                Serdes.Long() // serde for aggregated value
+            );
+
+            KStream<String, String> joined = source1.leftJoin(source2,
+                (record1, record2) -> record1.get("user") + "-" + record2.get("region");
+            );
+        </pre>
+
+        <h5><a id="streams_dsl_sink" href="#streams_dsl_sink">Write streams back to Kafka</a></h5>
+
+        <p>
+        At the end of the processing, users can choose to (continuously) write the final resulted streams back to a Kafka topic through
+        <code>KStream.to</code> and <code>KTable.to</code>.
+        </p>
+
+        <pre>
+            joined.to("topic4");
+        </pre>
+
+        If your application needs to continue reading and processing the records after they have been materialized
+        to a topic via <code>to</code> above, one option is to construct a new stream that reads from the output topic;
+        Kafka Streams provides a convenience method called <code>through</code>:
+
+        <pre>
+            // equivalent to
+            //
+            // joined.to("topic4");
+            // materialized = builder.stream("topic4");
+            KStream<String, String> materialized = joined.through("topic4");
+        </pre>
+
+
+        <br>
+        <p>
+        Besides defining the topology, developers will also need to configure their applications
+        in <code>StreamsConfig</code> before running it. A complete list of
+        Kafka Streams configs can be found <a href="#streamsconfigs"><b>here</b></a>.
+        </p>
+</script>
+
+<!--#include virtual="../includes/_header.htm" -->
+<!--#include virtual="../includes/_top.htm" -->
+<div class="content documentation documentation--current">
+	<!--#include virtual="../includes/_nav.htm" -->
+	<div class="right">
+		<!--#include virtual="../includes/_docs_banner.htm" -->
+        <ul class="breadcrumbs">
+            <li><a href="/documentation">Documentation</a></li>
+        </ul>
+        <div class="p-streams"></div>
+    </div>
+</div>
+<!--#include virtual="../includes/_footer.htm" -->
+<script>
+$(function() {
+  // Show selected style on nav item
+  $('.b-nav__streams').addClass('selected');
+
+  // Display docs subnav items
+  $('.b-nav__docs').parent().toggleClass('nav__item__with__subs--expanded');
+});
+</script>


[7/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/connect.html
----------------------------------------------------------------------
diff --git a/docs/connect.html b/docs/connect.html
index d3fc7d7..23e168c 100644
--- a/docs/connect.html
+++ b/docs/connect.html
@@ -15,411 +15,415 @@
   ~ limitations under the License.
   ~-->
 
-<h3><a id="connect_overview" href="#connect_overview">8.1 Overview</a></h3>
+<script id="connect-template" type="text/x-handlebars-template">
+    <h3><a id="connect_overview" href="#connect_overview">8.1 Overview</a></h3>
 
-Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other systems. It makes it simple to quickly define <i>connectors</i> 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 is a tool for scalably and reliably streaming data between Apache Kafka and other systems. It makes it simple to quickly define <i>connectors</i> 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:
-<ul>
-    <li><b>A common framework for Kafka connectors</b> - Kafka Connect standardizes integration of other data systems with Kafka, simplifying connector development, deployment, and management</li>
-    <li><b>Distributed and standalone modes</b> - scale up to a large, centrally managed service supporting an entire organization or scale down to development, testing, and small production deployments</li>
-    <li><b>REST interface</b> - submit and manage connectors to your Kafka Connect cluster via an easy to use REST API</li>
-    <li><b>Automatic offset management</b> - with just a little information from connectors, Kafka Connect can manage the offset commit process automatically so connector developers do not need to worry about this error prone part of connector development</li>
-    <li><b>Distributed and scalable by default</b> - Kafka Connect builds on the existing group management protocol. More workers can be added to scale up a Kafka Connect cluster.</li>
-    <li><b>Streaming/batch integration</b> - leveraging Kafka's existing capabilities, Kafka Connect is an ideal solution for bridging streaming and batch data systems</li>
-</ul>
+    Kafka Connect features include:
+    <ul>
+        <li><b>A common framework for Kafka connectors</b> - Kafka Connect standardizes integration of other data systems with Kafka, simplifying connector development, deployment, and management</li>
+        <li><b>Distributed and standalone modes</b> - scale up to a large, centrally managed service supporting an entire organization or scale down to development, testing, and small production deployments</li>
+        <li><b>REST interface</b> - submit and manage connectors to your Kafka Connect cluster via an easy to use REST API</li>
+        <li><b>Automatic offset management</b> - with just a little information from connectors, Kafka Connect can manage the offset commit process automatically so connector developers do not need to worry about this error prone part of connector development</li>
+        <li><b>Distributed and scalable by default</b> - Kafka Connect builds on the existing group management protocol. More workers can be added to scale up a Kafka Connect cluster.</li>
+        <li><b>Streaming/batch integration</b> - leveraging Kafka's existing capabilities, Kafka Connect is an ideal solution for bridging streaming and batch data systems</li>
+    </ul>
 
-<h3><a id="connect_user" href="#connect_user">8.2 User Guide</a></h3>
+    <h3><a id="connect_user" href="#connect_user">8.2 User Guide</a></h3>
 
-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.
+    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.
 
-<h4><a id="connect_running" href="#connect_running">Running Kafka Connect</a></h4>
+    <h4><a id="connect_running" href="#connect_running">Running Kafka Connect</a></h4>
 
-Kafka Connect currently supports two modes of execution: standalone (single process) and distributed.
+    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:
+    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:
 
-<pre>
-&gt; bin/connect-standalone.sh config/connect-standalone.properties connector1.properties [connector2.properties ...]
-</pre>
+    <pre>
+    &gt; bin/connect-standalone.sh config/connect-standalone.properties connector1.properties [connector2.properties ...]
+    </pre>
 
-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 <code>config/server.properties</code>. It will require tweaking to use with a different configuration or production deployment. All workers (both standalone and distributed) require a few configs:
-<ul>
-    <li><code>bootstrap.servers</code> - List of Kafka servers used to bootstrap connections to Kafka</li>
-    <li><code>key.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
-    <li><code>value.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
-</ul>
+    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 <code>config/server.properties</code>. It will require tweaking to use with a different configuration or production deployment. All workers (both standalone and distributed) require a few configs:
+    <ul>
+        <li><code>bootstrap.servers</code> - List of Kafka servers used to bootstrap connections to Kafka</li>
+        <li><code>key.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
+        <li><code>value.converter</code> - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.</li>
+    </ul>
 
-The important configuration options specific to standalone mode are:
-<ul>
-    <li><code>offset.storage.file.filename</code> - File to store offset data in</li>
-</ul>
+    The important configuration options specific to standalone mode are:
+    <ul>
+        <li><code>offset.storage.file.filename</code> - File to store offset data in</li>
+    </ul>
 
-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).
+    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:
+    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:
 
-<pre>
-&gt; bin/connect-distributed.sh config/connect-distributed.properties
-</pre>
+    <pre>
+    &gt; bin/connect-distributed.sh config/connect-distributed.properties
+    </pre>
 
-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.
+    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, in addition to the common settings mentioned above, are critical to set before starting your cluster:
-<ul>
-    <li><code>group.id</code> (default <code>connect-cluster</code>) - unique name for the cluster, used in forming the Connect cluster group; note that this <b>must not conflict</b> with consumer group IDs</li>
-    <li><code>config.storage.topic</code> (default <code>connect-configs</code>) - topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, compacted topic. You may need to manually create the topic to ensure the correct configuration as auto created topics may have multiple partitions or be automatically configured for deletion rather than compaction</li>
-    <li><code>offset.storage.topic</code> (default <code>connect-offsets</code>) - topic to use for storing offsets; this topic should have many partitions, be replicated, and be configured for compaction</li>
-    <li><code>status.storage.topic</code> (default <code>connect-status</code>) - topic to use for storing statuses; this topic can have multiple partitions, and should be replicated and configured for compaction</li>
-</ul>
+    In particular, the following configuration parameters, in addition to the common settings mentioned above, are critical to set before starting your cluster:
+    <ul>
+        <li><code>group.id</code> (default <code>connect-cluster</code>) - unique name for the cluster, used in forming the Connect cluster group; note that this <b>must not conflict</b> with consumer group IDs</li>
+        <li><code>config.storage.topic</code> (default <code>connect-configs</code>) - topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, compacted topic. You may need to manually create the topic to ensure the correct configuration as auto created topics may have multiple partitions or be automatically configured for deletion rather than compaction</li>
+        <li><code>offset.storage.topic</code> (default <code>connect-offsets</code>) - topic to use for storing offsets; this topic should have many partitions, be replicated, and be configured for compaction</li>
+        <li><code>status.storage.topic</code> (default <code>connect-status</code>) - topic to use for storing statuses; this topic can have multiple partitions, and should be replicated and configured for compaction</li>
+    </ul>
 
-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. 
+    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. 
 
 
-<h4><a id="connect_configuring" href="#connect_configuring">Configuring Connectors</a></h4>
+    <h4><a id="connect_configuring" href="#connect_configuring">Configuring Connectors</a></h4>
 
-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.
+    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:
+    Most configurations are connector dependent, so they can't be outlined here. However, there are a few common options:
 
-<ul>
-    <li><code>name</code> - Unique name for the connector. Attempting to register again with the same name will fail.</li>
-    <li><code>connector.class</code> - The Java class for the connector</li>
-    <li><code>tasks.max</code> - The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism.</li>
-    <li><code>key.converter</code> - (optional) Override the default key converter set by the worker.</li>
-    <li><code>value.converter</code> - (optional) Override the default value converter set by the worker.</li>
-</ul>
+    <ul>
+        <li><code>name</code> - Unique name for the connector. Attempting to register again with the same name will fail.</li>
+        <li><code>connector.class</code> - The Java class for the connector</li>
+        <li><code>tasks.max</code> - The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism.</li>
+        <li><code>key.converter</code> - (optional) Override the default key converter set by the worker.</li>
+        <li><code>value.converter</code> - (optional) Override the default value converter set by the worker.</li>
+    </ul>
 
-The <code>connector.class</code> 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.
+    The <code>connector.class</code> 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:
-<ul>
-    <li><code>topics</code> - A list of topics to use as input for this connector</li>
-</ul>
+    Sink connectors also have one additional option to control their input:
+    <ul>
+        <li><code>topics</code> - A list of topics to use as input for this connector</li>
+    </ul>
 
-For any other options, you should consult the documentation for the connector.
+    For any other options, you should consult the documentation for the connector.
 
-<h4><a id="connect_rest" href="#connect_rest">REST API</a></h4>
+    <h4><a id="connect_rest" href="#connect_rest">REST API</a></h4>
 
-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:
+    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:
 
-<ul>
-    <li><code>GET /connectors</code> - return a list of active connectors</li>
-    <li><code>POST /connectors</code> - create a new connector; the request body should be a JSON object containing a string <code>name</code> field and an object <code>config</code> field with the connector configuration parameters</li>
-    <li><code>GET /connectors/{name}</code> - get information about a specific connector</li>
-    <li><code>GET /connectors/{name}/config</code> - get the configuration parameters for a specific connector</li>
-    <li><code>PUT /connectors/{name}/config</code> - update the configuration parameters for a specific connector</li>
-    <li><code>GET /connectors/{name}/status</code> - get current status of the connector, including if it is running, failed, paused, etc., which worker it is assigned to, error information if it has failed, and the state of all its tasks</li>
-    <li><code>GET /connectors/{name}/tasks</code> - get a list of tasks currently running for a connector</li>
-    <li><code>GET /connectors/{name}/tasks/{taskid}/status</code> - get current status of the task, including if it is running, failed, paused, etc., which worker it is assigned to, and error information if it has failed</li>
-    <li><code>PUT /connectors/{name}/pause</code> - pause the connector and its tasks, which stops message processing until the connector is resumed</li>
-    <li><code>PUT /connectors/{name}/resume</code> - resume a paused connector (or do nothing if the connector is not paused)</li>
-    <li><code>POST /connectors/{name}/restart</code> - restart a connector (typically because it has failed)</li>
-    <li><code>POST /connectors/{name}/tasks/{taskId}/restart</code> - restart an individual task (typically because it has failed)</li>
-    <li><code>DELETE /connectors/{name}</code> - delete a connector, halting all tasks and deleting its configuration</li>
-</ul>
+    <ul>
+        <li><code>GET /connectors</code> - return a list of active connectors</li>
+        <li><code>POST /connectors</code> - create a new connector; the request body should be a JSON object containing a string <code>name</code> field and an object <code>config</code> field with the connector configuration parameters</li>
+        <li><code>GET /connectors/{name}</code> - get information about a specific connector</li>
+        <li><code>GET /connectors/{name}/config</code> - get the configuration parameters for a specific connector</li>
+        <li><code>PUT /connectors/{name}/config</code> - update the configuration parameters for a specific connector</li>
+        <li><code>GET /connectors/{name}/status</code> - get current status of the connector, including if it is running, failed, paused, etc., which worker it is assigned to, error information if it has failed, and the state of all its tasks</li>
+        <li><code>GET /connectors/{name}/tasks</code> - get a list of tasks currently running for a connector</li>
+        <li><code>GET /connectors/{name}/tasks/{taskid}/status</code> - get current status of the task, including if it is running, failed, paused, etc., which worker it is assigned to, and error information if it has failed</li>
+        <li><code>PUT /connectors/{name}/pause</code> - pause the connector and its tasks, which stops message processing until the connector is resumed</li>
+        <li><code>PUT /connectors/{name}/resume</code> - resume a paused connector (or do nothing if the connector is not paused)</li>
+        <li><code>POST /connectors/{name}/restart</code> - restart a connector (typically because it has failed)</li>
+        <li><code>POST /connectors/{name}/tasks/{taskId}/restart</code> - restart an individual task (typically because it has failed)</li>
+        <li><code>DELETE /connectors/{name}</code> - delete a connector, halting all tasks and deleting its configuration</li>
+    </ul>
 
-Kafka Connect also provides a REST API for getting information about connector plugins:
+    Kafka Connect also provides a REST API for getting information about connector plugins:
 
-<ul>
-    <li><code>GET /connector-plugins</code>- return a list of connector plugins installed in the Kafka Connect cluster. Note that the API only checks for connectors on the worker that handles the request, which means you may see inconsistent results, especially during a rolling upgrade if you add new connector jars</li>
-    <li><code>PUT /connector-plugins/{connector-type}/config/validate</code> - validate the provided configuration values against the configuration definition. This API performs per config validation, returns suggested values and error messages during validation.</li>
-</ul>
+    <ul>
+        <li><code>GET /connector-plugins</code>- return a list of connector plugins installed in the Kafka Connect cluster. Note that the API only checks for connectors on the worker that handles the request, which means you may see inconsistent results, especially during a rolling upgrade if you add new connector jars</li>
+        <li><code>PUT /connector-plugins/{connector-type}/config/validate</code> - validate the provided configuration values against the configuration definition. This API performs per config validation, returns suggested values and error messages during validation.</li>
+    </ul>
 
-<h3><a id="connect_development" href="#connect_development">8.3 Connector Development Guide</a></h3>
+    <h3><a id="connect_development" href="#connect_development">8.3 Connector Development Guide</a></h3>
 
-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.
+    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.
 
-<h4><a id="connect_concepts" href="#connect_concepts">Core Concepts and APIs</a></h4>
+    <h4><a id="connect_concepts" href="#connect_concepts">Core Concepts and APIs</a></h4>
 
-<h5><a id="connect_connectorsandtasks" href="#connect_connectorsandtasks">Connectors and Tasks</a></h5>
+    <h5><a id="connect_connectorsandtasks" href="#connect_connectorsandtasks">Connectors and Tasks</a></h5>
 
-To copy data between Kafka and another system, users create a <code>Connector</code> for the system they want to pull data from or push data to. Connectors come in two flavors: <code>SourceConnectors</code> import data from another system (e.g. <code>JDBCSourceConnector</code> would import a relational database into Kafka) and <code>SinkConnectors</code> export data (e.g. <code>HDFSSinkConnector</code> would export the contents of a Kafka topic to an HDFS file).
+    To copy data between Kafka and another system, users create a <code>Connector</code> for the system they want to pull data from or push data to. Connectors come in two flavors: <code>SourceConnectors</code> import data from another system (e.g. <code>JDBCSourceConnector</code> would import a relational database into Kafka) and <code>SinkConnectors</code> export data (e.g. <code>HDFSSinkConnector</code> would export the contents of a Kafka topic to an HDFS file).
 
-<code>Connectors</code> do not perform any data copying themselves: their configuration describes the data to be copied, and the <code>Connector</code> is responsible for breaking that job into a set of <code>Tasks</code> that can be distributed to workers. These <code>Tasks</code> also come in two corresponding flavors: <code>SourceTask</code> and <code>SinkTask</code>.
+    <code>Connectors</code> do not perform any data copying themselves: their configuration describes the data to be copied, and the <code>Connector</code> is responsible for breaking that job into a set of <code>Tasks</code> that can be distributed to workers. These <code>Tasks</code> also come in two corresponding flavors: <code>SourceTask</code> and <code>SinkTask</code>.
 
-With an assignment in hand, each <code>Task</code> 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.
+    With an assignment in hand, each <code>Task</code> 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.
 
 
-<h5><a id="connect_streamsandrecords" href="#connect_streamsandrecords">Streams and Records</a></h5>
+    <h5><a id="connect_streamsandrecords" href="#connect_streamsandrecords">Streams and Records</a></h5>
 
-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.
+    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.
+    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.
 
-<h5><a id="connect_dynamicconnectors" href="#connect_dynamicconnectors">Dynamic Connectors</a></h5>
+    <h5><a id="connect_dynamicconnectors" href="#connect_dynamicconnectors">Dynamic Connectors</a></h5>
 
-Not all jobs are static, so <code>Connector</code> implementations are also responsible for monitoring the external system for any changes that might require reconfiguration. For example, in the <code>JDBCSourceConnector</code> example, the <code>Connector</code> might assign a set of tables to each <code>Task</code>. When a new table is created, it must discover this so it can assign the new table to one of the <code>Tasks</code> by updating its configuration. When it notices a change that requires reconfiguration (or a change in the number of <code>Tasks</code>), it notifies the framework and the framework updates any corresponding <code>Tasks</code>.
+    Not all jobs are static, so <code>Connector</code> implementations are also responsible for monitoring the external system for any changes that might require reconfiguration. For example, in the <code>JDBCSourceConnector</code> example, the <code>Connector</code> might assign a set of tables to each <code>Task</code>. When a new table is created, it must discover this so it can assign the new table to one of the <code>Tasks</code> by updating its configuration. When it notices a change that requires reconfiguration (or a change in the number of <code>Tasks</code>), it notifies the framework and the framework updates any corresponding <code>Tasks</code>.
 
 
-<h4><a id="connect_developing" href="#connect_developing">Developing a Simple Connector</a></h4>
+    <h4><a id="connect_developing" href="#connect_developing">Developing a Simple Connector</a></h4>
 
-Developing a connector only requires implementing two interfaces, the <code>Connector</code> and <code>Task</code>. A simple example is included with the source code for Kafka in the <code>file</code> package. This connector is meant for use in standalone mode and has implementations of a <code>SourceConnector</code>/<code>SourceTask</code> to read each line of a file and emit it as a record and a <code>SinkConnector</code>/<code>SinkTask</code> that writes each record to a file.
+    Developing a connector only requires implementing two interfaces, the <code>Connector</code> and <code>Task</code>. A simple example is included with the source code for Kafka in the <code>file</code> package. This connector is meant for use in standalone mode and has implementations of a <code>SourceConnector</code>/<code>SourceTask</code> to read each line of a file and emit it as a record and a <code>SinkConnector</code>/<code>SinkTask</code> 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.
+    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.
 
-<h5><a id="connect_connectorexample" href="#connect_connectorexample">Connector Example</a></h5>
+    <h5><a id="connect_connectorexample" href="#connect_connectorexample">Connector Example</a></h5>
 
-We'll cover the <code>SourceConnector</code> as a simple example. <code>SinkConnector</code> implementations are very similar. Start by creating the class that inherits from <code>SourceConnector</code> and add a couple of fields that will store parsed configuration information (the filename to read from and the topic to send data to):
+    We'll cover the <code>SourceConnector</code> as a simple example. <code>SinkConnector</code> implementations are very similar. Start by creating the class that inherits from <code>SourceConnector</code> and add a couple of fields that will store parsed configuration information (the filename to read from and the topic to send data to):
 
-<pre>
-public class FileStreamSourceConnector extends SourceConnector {
-    private String filename;
-    private String topic;
-</pre>
+    <pre>
+    public class FileStreamSourceConnector extends SourceConnector {
+        private String filename;
+        private String topic;
+    </pre>
 
-The easiest method to fill in is <code>getTaskClass()</code>, which defines the class that should be instantiated in worker processes to actually read the data:
+    The easiest method to fill in is <code>getTaskClass()</code>, which defines the class that should be instantiated in worker processes to actually read the data:
 
-<pre>
-@Override
-public Class&lt;? extends Task&gt; getTaskClass() {
-    return FileStreamSourceTask.class;
-}
-</pre>
+    <pre>
+    @Override
+    public Class&lt;? extends Task&gt; getTaskClass() {
+        return FileStreamSourceTask.class;
+    }
+    </pre>
 
-We will define the <code>FileStreamSourceTask</code> class below. Next, we add some standard lifecycle methods, <code>start()</code> and <code>stop()</code>:
+    We will define the <code>FileStreamSourceTask</code> class below. Next, we add some standard lifecycle methods, <code>start()</code> and <code>stop()</code>:
 
-<pre>
-@Override
-public void start(Map&lt;String, String&gt; props) {
-    // The complete version includes error handling as well.
-    filename = props.get(FILE_CONFIG);
-    topic = props.get(TOPIC_CONFIG);
-}
+    <pre>
+    @Override
+    public void start(Map&lt;String, String&gt; 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.
-}
-</pre>
+    @Override
+    public void stop() {
+        // Nothing to do since no background monitoring is required.
+    }
+    </pre>
 
-Finally, the real core of the implementation is in <code>taskConfigs()</code>. In this case we are only
-handling a single file, so even though we may be permitted to generate more tasks as per the
-<code>maxTasks</code> argument, we return a list with only one entry:
+    Finally, the real core of the implementation is in <code>taskConfigs()</code>. In this case we are only
+    handling a single file, so even though we may be permitted to generate more tasks as per the
+    <code>maxTasks</code> argument, we return a list with only one entry:
 
-<pre>
-@Override
-public List&lt;Map&lt;String, String&gt;&gt; taskConfigs(int maxTasks) {
-    ArrayList&lt;Map&lt;String, String&gt;&gt; configs = new ArrayList&lt;&gt;();
-    // Only one input stream makes sense.
-    Map&lt;String, String&gt; config = new HashMap&lt;&gt;();
-    if (filename != null)
-        config.put(FILE_CONFIG, filename);
-    config.put(TOPIC_CONFIG, topic);
-    configs.add(config);
-    return configs;
-}
-</pre>
+    <pre>
+    @Override
+    public List&lt;Map&lt;String, String&gt;&gt; taskConfigs(int maxTasks) {
+        ArrayList&lt;Map&lt;String, String&gt;&gt; configs = new ArrayList&lt;&gt;();
+        // Only one input stream makes sense.
+        Map&lt;String, String&gt; config = new HashMap&lt;&gt;();
+        if (filename != null)
+            config.put(FILE_CONFIG, filename);
+        config.put(TOPIC_CONFIG, topic);
+        configs.add(config);
+        return configs;
+    }
+    </pre>
 
-Although not used in the example, <code>SourceTask</code> also provides two APIs to commit offsets in the source system: <code>commit</code> and <code>commitRecord</code>. 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 <code>commit</code> API stores the offsets in the source system, up to the offsets that have been returned by <code>poll</code>. The implementation of this API should block until the commit is complete. The <code>commitRecord</code> API saves the offset in the source system for each <code>SourceRecord</code> after it is written to Kafka. As Kafka Connect will record offsets automatically, <code>SourceTask</code>s 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.
+    Although not used in the example, <code>SourceTask</code> also provides two APIs to commit offsets in the source system: <code>commit</code> and <code>commitRecord</code>. 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 <code>commit</code> API stores the offsets in the source system, up to the offsets that have been returned by <code>poll</code>. The implementation of this API should block until the commit is complete. The <code>commitRecord</code> API saves the offset in the source system for each <code>SourceRecord</code> after it is written to Kafka. As Kafka Connect will record offsets automatically, <code>SourceTask</code>s 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 <code>ConnectorUtils</code> to simplify these cases.
+    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 <code>ConnectorUtils</code> 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.
+    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.
 
-<h5><a id="connect_taskexample" href="#connect_taskexample">Task Example - Source Task</a></h5>
+    <h5><a id="connect_taskexample" href="#connect_taskexample">Task Example - Source Task</a></h5>
 
-Next we'll describe the implementation of the corresponding <code>SourceTask</code>. 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.
+    Next we'll describe the implementation of the corresponding <code>SourceTask</code>. 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 <code>Task</code> class. It also has some standard lifecycle methods:
+    Just as with the connector, we need to create a class inheriting from the appropriate base <code>Task</code> class. It also has some standard lifecycle methods:
 
 
-<pre>
-public class FileStreamSourceTask extends SourceTask {
-    String filename;
-    InputStream stream;
-    String topic;
+    <pre>
+    public class FileStreamSourceTask extends SourceTask {
+        String filename;
+        InputStream stream;
+        String topic;
 
-    @Override
-    public void start(Map&lt;String, String&gt; props) {
-        filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
-        stream = openOrThrowError(filename);
-        topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
-    }
+        @Override
+        public void start(Map&lt;String, String&gt; props) {
+            filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
+            stream = openOrThrowError(filename);
+            topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
+        }
+
+        @Override
+        public synchronized void stop() {
+            stream.close();
+        }
+    </pre>
 
+    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 <code>start()</code> method does not yet handle resuming from a previous offset, which will be addressed in a later section. Second, the <code>stop()</code> method is synchronized. This will be necessary because <code>SourceTasks</code> 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 <code>poll()</code> method which gets events from the input system and returns a <code>List&lt;SourceRecord&gt;</code>:
+
+    <pre>
     @Override
-    public synchronized void stop() {
-        stream.close();
-    }
-</pre>
-
-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 <code>start()</code> method does not yet handle resuming from a previous offset, which will be addressed in a later section. Second, the <code>stop()</code> method is synchronized. This will be necessary because <code>SourceTasks</code> 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 <code>poll()</code> method which gets events from the input system and returns a <code>List&lt;SourceRecord&gt;</code>:
-
-<pre>
-@Override
-public List&lt;SourceRecord&gt; poll() throws InterruptedException {
-    try {
-        ArrayList&lt;SourceRecord&gt; records = new ArrayList&lt;&gt;();
-        while (streamValid(stream) &amp;&amp; records.isEmpty()) {
-            LineAndOffset line = readToNextLine(stream);
-            if (line != null) {
-                Map&lt;String, Object&gt; sourcePartition = Collections.singletonMap("filename", filename);
-                Map&lt;String, Object&gt; sourceOffset = Collections.singletonMap("position", streamOffset);
-                records.add(new SourceRecord(sourcePartition, sourceOffset, topic, Schema.STRING_SCHEMA, line));
-            } else {
-                Thread.sleep(1);
+    public List&lt;SourceRecord&gt; poll() throws InterruptedException {
+        try {
+            ArrayList&lt;SourceRecord&gt; records = new ArrayList&lt;&gt;();
+            while (streamValid(stream) &amp;&amp; records.isEmpty()) {
+                LineAndOffset line = readToNextLine(stream);
+                if (line != null) {
+                    Map&lt;String, Object&gt; sourcePartition = Collections.singletonMap("filename", filename);
+                    Map&lt;String, Object&gt; 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 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;
     }
-    return null;
-}
-</pre>
+    </pre>
 
-Again, we've omitted some details, but we can see the important steps: the <code>poll()</code> 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 <code>SourceRecord</code> 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 <code>SourceRecord</code> constructor can also include a specific output partition and a key.
+    Again, we've omitted some details, but we can see the important steps: the <code>poll()</code> 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 <code>SourceRecord</code> 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 <code>SourceRecord</code> constructor can also include a specific output partition and a key.
 
-Note that this implementation uses the normal Java <code>InputStream</code> 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 <code>poll()</code> 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.
+    Note that this implementation uses the normal Java <code>InputStream</code> 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 <code>poll()</code> 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.
 
-<h5><a id="connect_sinktasks" href="#connect_sinktasks">Sink Tasks</a></h5>
+    <h5><a id="connect_sinktasks" href="#connect_sinktasks">Sink Tasks</a></h5>
 
-The previous section described how to implement a simple <code>SourceTask</code>. Unlike <code>SourceConnector</code> and <code>SinkConnector</code>, <code>SourceTask</code> and <code>SinkTask</code> have very different interfaces because <code>SourceTask</code> uses a pull interface and <code>SinkTask</code> uses a push interface. Both share the common lifecycle methods, but the <code>SinkTask</code> interface is quite different:
+    The previous section described how to implement a simple <code>SourceTask</code>. Unlike <code>SourceConnector</code> and <code>SinkConnector</code>, <code>SourceTask</code> and <code>SinkTask</code> have very different interfaces because <code>SourceTask</code> uses a pull interface and <code>SinkTask</code> uses a push interface. Both share the common lifecycle methods, but the <code>SinkTask</code> interface is quite different:
 
-<pre>
-public abstract class SinkTask implements Task {
-    public void initialize(SinkTaskContext context) {
-        this.context = context;
-    }
+    <pre>
+    public abstract class SinkTask implements Task {
+        public void initialize(SinkTaskContext context) {
+            this.context = context;
+        }
 
-    public abstract void put(Collection&lt;SinkRecord&gt; records);
-     
-    public abstract void flush(Map&lt;TopicPartition, Long&gt; offsets);
-</pre>
+        public abstract void put(Collection&lt;SinkRecord&gt; records);
+        
+        public abstract void flush(Map&lt;TopicPartition, Long&gt; offsets);
+    </pre>
 
-The <code>SinkTask</code> documentation contains full details, but this interface is nearly as simple as the <code>SourceTask</code>. The <code>put()</code> method should contain most of the implementation, accepting sets of <code>SinkRecords</code>, 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 <code>SinkRecords</code> contain essentially the same information as <code>SourceRecords</code>: Kafka topic, partition, offset and the event key and value.
+    The <code>SinkTask</code> documentation contains full details, but this interface is nearly as simple as the <code>SourceTask</code>. The <code>put()</code> method should contain most of the implementation, accepting sets of <code>SinkRecords</code>, 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 <code>SinkRecords</code> contain essentially the same information as <code>SourceRecords</code>: Kafka topic, partition, offset and the event key and value.
 
-The <code>flush()</code> 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 <code>offsets</code> 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 <code>flush()</code> operation atomically commits the data and offsets to a final location in HDFS.
+    The <code>flush()</code> 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 <code>offsets</code> 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 <code>flush()</code> operation atomically commits the data and offsets to a final location in HDFS.
 
 
-<h5><a id="connect_resuming" href="#connect_resuming">Resuming from Previous Offsets</a></h5>
+    <h5><a id="connect_resuming" href="#connect_resuming">Resuming from Previous Offsets</a></h5>
 
-The <code>SourceTask</code> 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.
+    The <code>SourceTask</code> 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 <code>SourceContext</code> passed into its <code>initialize()</code> method to access the offset data. In <code>initialize()</code>, we would add a bit more code to read the offset (if it exists) and seek to that position:
+    To correctly resume upon startup, the task can use the <code>SourceContext</code> passed into its <code>initialize()</code> method to access the offset data. In <code>initialize()</code>, we would add a bit more code to read the offset (if it exists) and seek to that position:
 
-<pre>
-    stream = new FileInputStream(filename);
-    Map&lt;String, Object&gt; offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
-    if (offset != null) {
-        Long lastRecordedOffset = (Long) offset.get("position");
-        if (lastRecordedOffset != null)
-            seekToOffset(stream, lastRecordedOffset);
-    }
-</pre>
+    <pre>
+        stream = new FileInputStream(filename);
+        Map&lt;String, Object&gt; offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
+        if (offset != null) {
+            Long lastRecordedOffset = (Long) offset.get("position");
+            if (lastRecordedOffset != null)
+                seekToOffset(stream, lastRecordedOffset);
+        }
+    </pre>
 
-Of course, you might need to read many keys for each of the input streams. The <code>OffsetStorageReader</code> 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.
+    Of course, you might need to read many keys for each of the input streams. The <code>OffsetStorageReader</code> 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.
 
-<h4><a id="connect_dynamicio" href="#connect_dynamicio">Dynamic Input/Output Streams</a></h4>
+    <h4><a id="connect_dynamicio" href="#connect_dynamicio">Dynamic Input/Output Streams</a></h4>
 
-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.
+    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 <code>ConnectorContext</code> object that reconfiguration is necessary. For example, in a <code>SourceConnector</code>:
+    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 <code>ConnectorContext</code> object that reconfiguration is necessary. For example, in a <code>SourceConnector</code>:
 
-<pre>
-    if (inputsChanged())
-        this.context.requestTaskReconfiguration();
-</pre>
+    <pre>
+        if (inputsChanged())
+            this.context.requestTaskReconfiguration();
+    </pre>
 
-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 <code>SourceConnector</code> 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.
+    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 <code>SourceConnector</code> 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 <code>Connector</code> 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 <code>Task</code> encounters the issue before the <code>Connector</code>, which will be common if the <code>Connector</code> needs to poll for changes, the <code>Task</code> will need to handle the subsequent error. Thankfully, this can usually be handled simply by catching and handling the appropriate exception.
+    Ideally this code for monitoring changes would be isolated to the <code>Connector</code> 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 <code>Task</code> encounters the issue before the <code>Connector</code>, which will be common if the <code>Connector</code> needs to poll for changes, the <code>Task</code> will need to handle the subsequent error. Thankfully, this can usually be handled simply by catching and handling the appropriate exception.
 
-<code>SinkConnectors</code> 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. <code>SinkTasks</code> 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 <code>SinkTasks</code> seeing a new input stream for the first time and simultaneously trying to create the new resource. <code>SinkConnectors</code>, on the other hand, will generally require no special code for handling a dynamic set of streams.
+    <code>SinkConnectors</code> 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. <code>SinkTasks</code> 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 <code>SinkTasks</code> seeing a new input stream for the first time and simultaneously trying to create the new resource. <code>SinkConnectors</code>, on the other hand, will generally require no special code for handling a dynamic set of streams.
 
-<h4><a id="connect_configs" href="#connect_configs">Connect Configuration Validation</a></h4>
+    <h4><a id="connect_configs" href="#connect_configs">Connect Configuration Validation</a></h4>
 
-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 <code>config()</code> to expose the configuration definition to the framework.
+    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 <code>config()</code> to expose the configuration definition to the framework.
 
-The following code in <code>FileStreamSourceConnector</code> defines the configuration and exposes it to the framework.
+    The following code in <code>FileStreamSourceConnector</code> defines the configuration and exposes it to the framework.
 
-<pre>
-    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");
+    <pre>
+        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;
-    }
-</pre>
+        public ConfigDef config() {
+            return CONFIG_DEF;
+        }
+    </pre>
 
-<code>ConfigDef</code> 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 <code>Validator</code> 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, <code>ConfigDef</code> allows you to specify the dependents of a configuration and to provide an implementation of <code>Recommender</code> to get valid values and set visibility of a configuration given the current configuration values.
+    <code>ConfigDef</code> 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 <code>Validator</code> 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, <code>ConfigDef</code> allows you to specify the dependents of a configuration and to provide an implementation of <code>Recommender</code> to get valid values and set visibility of a configuration given the current configuration values.
 
-Also, the <code>validate()</code> method in <code>Connector</code> 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.
+    Also, the <code>validate()</code> method in <code>Connector</code> 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.
 
-<h4><a id="connect_schemas" href="#connect_schemas">Working with Schemas</a></h4>
+    <h4><a id="connect_schemas" href="#connect_schemas">Working with Schemas</a></h4>
 
-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.
+    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 <code>data</code> API. Most structured records will need to interact with two classes in addition to primitive types: <code>Schema</code> and <code>Struct</code>.
+    To create more complex data, you'll need to work with the Kafka Connect <code>data</code> API. Most structured records will need to interact with two classes in addition to primitive types: <code>Schema</code> and <code>Struct</code>.
 
-The API documentation provides a complete reference, but here is a simple example creating a <code>Schema</code> and <code>Struct</code>:
+    The API documentation provides a complete reference, but here is a simple example creating a <code>Schema</code> and <code>Struct</code>:
 
-<pre>
-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();
+    <pre>
+    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);
-</pre>
+    Struct struct = new Struct(schema)
+        .put("name", "Barbara Liskov")
+        .put("age", 75);
+    </pre>
 
-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.
+    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 <code>ALTER TABLE</code> command. The connector must be able to detect these changes and react appropriately.
+    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 <code>ALTER TABLE</code> 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.
+    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.
 
-<h4><a id="connect_administration" href="#connect_administration">Kafka Connect Administration</a></h4>
+    <h4><a id="connect_administration" href="#connect_administration">Kafka Connect Administration</a></h4>
 
-<p>
-Kafka Connect's <a href="#connect_rest">REST layer</a> 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).
-</p>
+    <p>
+    Kafka Connect's <a href="#connect_rest">REST layer</a> 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).
+    </p>
 
-<p>
-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 <code>GET /connectors/file-source/status</code>) might produce output like the following:
-</p>
+    <p>
+    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 <code>GET /connectors/file-source/status</code>) might produce output like the following:
+    </p>
 
-<pre>
-{
-  "name": "file-source",
-  "connector": {
-    "state": "RUNNING",
-    "worker_id": "192.168.1.208:8083"
-  },
-  "tasks": [
+    <pre>
     {
-      "id": 0,
-      "state": "RUNNING",
-      "worker_id": "192.168.1.209:8083"
+    "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"
+        }
+    ]
     }
-  ]
-}
-</pre>
-
-<p>
-Connectors and their tasks publish status updates to a shared topic (configured with <code>status.storage.topic</code>) 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:
-</p>
-
-<ul>
-  <li><b>UNASSIGNED:</b> The connector/task has not yet been assigned to a worker.</li>
-  <li><b>RUNNING:</b> The connector/task is running.</li>
-  <li><b>PAUSED:</b> The connector/task has been administratively paused.</li>
-  <li><b>FAILED:</b> The connector/task has failed (usually by raising an exception, which is reported in the status output).</li>
-</ul>
-
-<p>
-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.
-</p>
-
-<p>
-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.
-</p>
+    </pre>
+
+    <p>
+    Connectors and their tasks publish status updates to a shared topic (configured with <code>status.storage.topic</code>) 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:
+    </p>
+
+    <ul>
+    <li><b>UNASSIGNED:</b> The connector/task has not yet been assigned to a worker.</li>
+    <li><b>RUNNING:</b> The connector/task is running.</li>
+    <li><b>PAUSED:</b> The connector/task has been administratively paused.</li>
+    <li><b>FAILED:</b> The connector/task has failed (usually by raising an exception, which is reported in the status output).</li>
+    </ul>
+
+    <p>
+    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.
+    </p>
+
+    <p>
+    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.
+    </p>
+</script>
+
+<div class="p-connect"></div>
\ No newline at end of file


[5/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/documentation.html
----------------------------------------------------------------------
diff --git a/docs/documentation.html b/docs/documentation.html
index 75c0467..e8516f9 100644
--- a/docs/documentation.html
+++ b/docs/documentation.html
@@ -15,6 +15,8 @@
  limitations under the License.
 -->
 
+<script><!--#include virtual="js/templateData.js" --></script>
+
 <!--#include virtual="../includes/_header.htm" -->
 <!--#include virtual="../includes/_top.htm" -->
 

http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/implementation.html
----------------------------------------------------------------------
diff --git a/docs/implementation.html b/docs/implementation.html
index 60ca0a1..48602f2 100644
--- a/docs/implementation.html
+++ b/docs/implementation.html
@@ -15,391 +15,395 @@
  limitations under the License.
 -->
 
-<h3><a id="apidesign" href="#apidesign">5.1 API Design</a></h3>
-
-<h4><a id="impl_producer" href="#impl_producer">Producer APIs</a></h4>
-
-<p>
-The Producer API that wraps the 2 low-level producers - <code>kafka.producer.SyncProducer</code> and <code>kafka.producer.async.AsyncProducer</code>.
-<pre>
-class Producer<T> {
-
-  /* Sends the data, partitioned by key to the topic using either the */
-  /* synchronous or the asynchronous producer */
-  public void send(kafka.javaapi.producer.ProducerData&lt;K,V&gt; 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&lt;kafka.javaapi.producer.ProducerData&lt;K,V&gt;&gt; producerData);
-
-  /* Closes the producer and cleans up */
-  public void close();
-
-}
-</pre>
-
-The goal is to expose all the producer functionality through a single API to the client.
-
-The Kafka producer
-<ul>
-<li>can handle queueing/buffering of multiple producer requests and asynchronous dispatch of the batched data:
-<p><code>kafka.producer.Producer</code> provides the ability to batch multiple produce requests (<code>producer.type=async</code>), before serializing and dispatching them to the appropriate kafka broker partition. The size of the batch can be controlled by a few config parameters. As events enter a queue, they are buffered in a queue, until either <code>queue.time</code> or <code>batch.size</code> is reached. A background thread (<code>kafka.producer.async.ProducerSendThread</code>) dequeues the batch of data and lets the <code>kafka.producer.EventHandler</code> serialize and send the data to the appropriate kafka broker partition. A custom event handler can be plugged in through the <code>event.handler</code> config parameter. At various stages of this producer queue pipeline, it is helpful to be able to inject callbacks, either for plugging in custom logging/tracing code or custom monitoring logic. This is possible by implementing the <code>kafka.producer.async.CallbackHandler</c
 ode> interface and setting <code>callback.handler</code> config parameter to that class.
-</p>
-</li>
-<li>handles the serialization of data through a user-specified <code>Encoder</code>:
-<pre>
-interface Encoder&lt;T&gt; {
-  public Message toMessage(T data);
-}
-</pre>
-<p>The default is the no-op <code>kafka.serializer.DefaultEncoder</code></p>
-</li>
-<li>provides software load balancing through an optionally user-specified <code>Partitioner</code>:
-<p>
-The routing decision is influenced by the <code>kafka.producer.Partitioner</code>.
-<pre>
-interface Partitioner&lt;T&gt; {
-   int partition(T key, int numPartitions);
-}
-</pre>
-The partition API uses the key and the number of available broker partitions to return a partition id. This id is used as an index into a sorted list of broker_ids and partitions to pick a broker partition for the producer request. The default partitioning strategy is <code>hash(key)%numPartitions</code>. If the key is null, then a random broker partition is picked. A custom partitioning strategy can also be plugged in using the <code>partitioner.class</code> config parameter.
-</p>
-</li>
-</ul>
-</p>
-
-<h4><a id="impl_consumer" href="#impl_consumer">Consumer APIs</a></h4>
-<p>
-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.
-</p>
-<p>
-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).
-</p>
-
-<h5><a id="impl_lowlevel" href="#impl_lowlevel">Low-level API</a></h5>
-<pre>
-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&lt;FetchRequest&gt; 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);
-}
-</pre>
-
-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.
-
-<h5><a id="impl_highlevel" href="#impl_highlevel">High-level API</a></h5>
-<pre>
-
-/* 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 &lt;topic, #streams&gt;
-   *  Output: a map of &lt;topic, list of message streams&gt;
-   */
-  public Map&lt;String,List&lt;KafkaStream&gt;&gt; createMessageStreams(Map&lt;String,Int&gt; 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&lt;KafkaStream&gt; createMessageStreamsByFilter(
-      TopicFilter topicFilter, int numStreams);
-
-  /* Commit the offsets of all messages consumed so far. */
-  public commitOffsets()
-
-  /* Shut down the connector */
-  public shutdown()
-}
-</pre>
-<p>
-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.
-</p>
-<p>
-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).
-</p>
-
-<h3><a id="networklayer" href="#networklayer">5.2 Network Layer</a></h3>
-<p>
-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 <code>MessageSet</code> interface a <code>writeTo</code> method. This allows the file-backed message set to use the more efficient <code>transferTo</code> implementation instead of an in-process buffered write. The threading model is a single acceptor thread and <i>N</i> processor threads which handle a fixed number of connections each. This design has been pretty thoroughly tested <a href="http://sna-projects.com/blog/2009/08/introducing-the-nio-socketserver-implementation">elsewhere</a> 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.
-</p>
-<h3><a id="messages" href="#messages">5.3 Messages</a></h3>
-<p>
-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:
-<ul>
-    <li> A CRC32 checksum to detect corruption or truncation. <li/>
-    <li> A format version. </li>
-    <li> An attributes identifier </li>
-    <li> A timestamp </li>
-</ul>
-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 <code>MessageSet</code> interface is simply an iterator over messages with specialized methods for bulk reading and writing to an NIO <code>Channel</code>.
-
-<h3><a id="messageformat" href="#messageformat">5.4 Message Format</a></h3>
-
-<pre>
+<script id="implementation-template" type="text/x-handlebars-template">
+    <h3><a id="apidesign" href="#apidesign">5.1 API Design</a></h3>
+
+    <h4><a id="impl_producer" href="#impl_producer">Producer APIs</a></h4>
+
+    <p>
+    The Producer API that wraps the 2 low-level producers - <code>kafka.producer.SyncProducer</code> and <code>kafka.producer.async.AsyncProducer</code>.
+    <pre>
+    class Producer<T> {
+
+    /* Sends the data, partitioned by key to the topic using either the */
+    /* synchronous or the asynchronous producer */
+    public void send(kafka.javaapi.producer.ProducerData&lt;K,V&gt; 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&lt;kafka.javaapi.producer.ProducerData&lt;K,V&gt;&gt; producerData);
+
+    /* Closes the producer and cleans up */
+    public void close();
+
+    }
+    </pre>
+
+    The goal is to expose all the producer functionality through a single API to the client.
+
+    The Kafka producer
+    <ul>
+    <li>can handle queueing/buffering of multiple producer requests and asynchronous dispatch of the batched data:
+    <p><code>kafka.producer.Producer</code> provides the ability to batch multiple produce requests (<code>producer.type=async</code>), before serializing and dispatching them to the appropriate kafka broker partition. The size of the batch can be controlled by a few config parameters. As events enter a queue, they are buffered in a queue, until either <code>queue.time</code> or <code>batch.size</code> is reached. A background thread (<code>kafka.producer.async.ProducerSendThread</code>) dequeues the batch of data and lets the <code>kafka.producer.EventHandler</code> serialize and send the data to the appropriate kafka broker partition. A custom event handler can be plugged in through the <code>event.handler</code> config parameter. At various stages of this producer queue pipeline, it is helpful to be able to inject callbacks, either for plugging in custom logging/tracing code or custom monitoring logic. This is possible by implementing the <code>kafka.producer.async.CallbackHandle
 r</code> interface and setting <code>callback.handler</code> config parameter to that class.
+    </p>
+    </li>
+    <li>handles the serialization of data through a user-specified <code>Encoder</code>:
+    <pre>
+    interface Encoder&lt;T&gt; {
+    public Message toMessage(T data);
+    }
+    </pre>
+    <p>The default is the no-op <code>kafka.serializer.DefaultEncoder</code></p>
+    </li>
+    <li>provides software load balancing through an optionally user-specified <code>Partitioner</code>:
+    <p>
+    The routing decision is influenced by the <code>kafka.producer.Partitioner</code>.
+    <pre>
+    interface Partitioner&lt;T&gt; {
+    int partition(T key, int numPartitions);
+    }
+    </pre>
+    The partition API uses the key and the number of available broker partitions to return a partition id. This id is used as an index into a sorted list of broker_ids and partitions to pick a broker partition for the producer request. The default partitioning strategy is <code>hash(key)%numPartitions</code>. If the key is null, then a random broker partition is picked. A custom partitioning strategy can also be plugged in using the <code>partitioner.class</code> config parameter.
+    </p>
+    </li>
+    </ul>
+    </p>
+
+    <h4><a id="impl_consumer" href="#impl_consumer">Consumer APIs</a></h4>
+    <p>
+    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.
+    </p>
+    <p>
+    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).
+    </p>
+
+    <h5><a id="impl_lowlevel" href="#impl_lowlevel">Low-level API</a></h5>
+    <pre>
+    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&lt;FetchRequest&gt; 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);
+    }
+    </pre>
+
+    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.
+
+    <h5><a id="impl_highlevel" href="#impl_highlevel">High-level API</a></h5>
+    <pre>
+
+    /* 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 &lt;topic, #streams&gt;
+    *  Output: a map of &lt;topic, list of message streams&gt;
+    */
+    public Map&lt;String,List&lt;KafkaStream&gt;&gt; createMessageStreams(Map&lt;String,Int&gt; topicCountMap);
+
     /**
-     * 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
-     */
-</pre>
-</p>
-<h3><a id="log" href="#log">5.5 Log</a></h3>
-<p>
-A log for a topic named "my_topic" with two partitions consists of two directories (namely <code>my_topic_0</code> and <code>my_topic_1</code>) 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 <i>N</i> storing the message length which is followed by the <i>N</i> message bytes. Each message is uniquely identified by a 64-bit integer <i>offset</i> 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 <i>S</i> bytes from the previous file where <i>S</i> is the max log file size given in the configuration.
-</p>
-<p>
-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:
-</p>
-<pre>
-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
-</pre>
-<p>
-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&mdash;both after all are monotonically increasing integers unique to a partition. Since the off
 set is hidden from the consumer API this decision is ultimately an implementation detail and we went with the more efficient approach.
-</p>
-<img class="centered" src="images/kafka_log.png">
-<h4><a id="impl_writes" href="#impl_writes">Writes</a></h4>
-<p>
-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: <i>M</i>, which gives the number of messages to write before forcing the OS to flush the file to disk, and <i>S</i>, which gives a number of seconds after which a flush is forced. This gives a durability guarantee of losing at most <i>M</i> messages or <i>S</i> seconds of data in the event of a system crash.
-</p>
-<h4><a id="impl_reads" href="#impl_reads">Reads</a></h4>
-<p>
-Reads are done by giving the 64-bit logical offset of a message and an <i>S</i>-byte max chunk size. This will return an iterator over the messages contained in the <i>S</i>-byte buffer. <i>S</i> 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.
-</p>
-<p>
-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.
-</p>
-<p>
-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.
-</p>
-
-<p> The following is the format of the results sent to the consumer.
-
-<pre>
-MessageSetSend (fetch result)
-
-total length     : 4 bytes
-error code       : 2 bytes
-message 1        : x bytes
-...
-message n        : x bytes
-</pre>
-
-<pre>
-MultiMessageSetSend (multiFetch result)
-
-total length       : 4 bytes
-error code         : 2 bytes
-messageSetSend 1
-...
-messageSetSend n
-</pre>
-<h4><a id="impl_deletes" href="#impl_deletes">Deletes</a></h4>
-<p>
-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 <i>N</i> days ago, though a policy which retained the last <i>N</i> 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.
-</p>
-<h4><a id="impl_guarantees" href="#impl_guarantees">Guarantees</a></h4>
-<p>
-The log provides a configuration parameter <i>M</i> 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.
-</p>
-<p>
-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).
-</p>
-
-<h3><a id="distributionimpl" href="#distributionimpl">5.6 Distribution</a></h3>
-<h4><a id="impl_offsettracking" href="#impl_offsettracking">Consumer Offset Tracking</a></h4>
-<p>
-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 <i>offset manager</i>. 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 c
 ontain 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 <a href="https://cwiki.apache.org/confluence/display/KAFKA/Committing+and+fetching+consumer+offsets+in+Kafka">code samples that explain how to issue OffsetCommitRequest and OffsetFetchRequest</a>.
-</p>
-
-<p>
-When the offset manager receives an OffsetCommitRequest, it appends the request to a special <a href="#compaction">compacted</a> Kafka topic named <i>__consumer_offsets</i>. 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.
-</p>
-
-<p>
-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.)
-</p>
-
-<h5><a id="offsetmigration" href="#offsetmigration">Migrating offsets from ZooKeeper to Kafka</a></h5>
-<p>
-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:
-<ol>
-   <li>Set <code>offsets.storage=kafka</code> and <code>dual.commit.enabled=true</code> in your consumer config.
-   </li>
-   <li>Do a rolling bounce of your consumers and then verify that your consumers are healthy.
-   </li>
-   <li>Set <code>dual.commit.enabled=false</code> in your consumer config.
-   </li>
-   <li>Do a rolling bounce of your consumers and then verify that your consumers are healthy.
-   </li>
-</ol>
-A roll-back (i.e., migrating from Kafka back to ZooKeeper) can also be performed using the above steps if you set <code>offsets.storage=zookeeper</code>.
-</p>
-
-<h4><a id="impl_zookeeper" href="#impl_zookeeper">ZooKeeper Directories</a></h4>
-<p>
-The following gives the ZooKeeper structures and algorithms used for co-ordination between consumers and brokers.
-</p>
-
-<h4><a id="impl_zknotation" href="#impl_zknotation">Notation</a></h4>
-<p>
-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".
-</p>
-
-<h4><a id="impl_zkbroker" href="#impl_zkbroker">Broker Node Registry</a></h4>
-<pre>
-/brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)
-</pre>
-<p>
-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.
-</p>
-<p>
-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).
-</p>
-<h4><a id="impl_zktopic" href="#impl_zktopic">Broker Topic Registry</a></h4>
-<pre>
-/brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)
-</pre>
-
-<p>
-Each broker registers itself under the topics it maintains and stores the number of partitions for that topic.
-</p>
-
-<h4><a id="impl_zkconsumers" href="#impl_zkconsumers">Consumers and Consumer Groups</a></h4>
-<p>
-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 <code>offsets.storage=zookeeper</code>. However, this offset storage mechanism will be deprecated in a future release. Therefore, it is recommended to <a href="#offsetmigration">migrate offsets storage to Kafka</a>.
-</p>
-
-<p>
-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.
-</p>
-
-<p>
-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.
-</p>
-
-<h4><a id="impl_zkconsumerid" href="#impl_zkconsumerid">Consumer Id Registry</a></h4>
-<p>
-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.
-<pre>
-/consumers/[group_id]/ids/[consumer_id] --> {"version":...,"subscription":{...:...},"pattern":...,"timestamp":...} (ephemeral node)
-</pre>
-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 &lt;topic, #streams&gt;. 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.
-</p>
-
-<h4><a id="impl_zkconsumeroffsets" href="#impl_zkconsumeroffsets">Consumer Offsets</a></h4>
-<p>
-Consumers track the maximum offset they have consumed in each partition. This value is stored in a ZooKeeper directory if <code>offsets.storage=zookeeper</code>.
-</p>
-<pre>
-/consumers/[group_id]/offsets/[topic]/[partition_id] --> offset_counter_value (persistent node)
-</pre>
-
-<h4><a id="impl_zkowner" href="#impl_zkowner">Partition Owner registry</a></h4>
-
-<p>
-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.
-</p>
-
-<pre>
-/consumers/[group_id]/owners/[topic]/[partition_id] --> consumer_node_id (ephemeral node)
-</pre>
-
-<h4><a id="impl_clusterid" href="#impl_clusterid">Cluster Id</a></h4>
-
-<p>
-    The cluster id is a unique and immutable identifier assigned to a Kafka cluster. The cluster id can have a maximum of 22 characters and the allowed characters are defined by the regular expression [a-zA-Z0-9_\-]+, which corresponds to the characters used by the URL-safe Base64 variant with no padding. Conceptually, it is auto-generated when a cluster is started for the first time.
-</p>
-<p>
-    Implementation-wise, it is generated when a broker with version 0.10.1 or later is successfully started for the first time. The broker tries to get the cluster id from the <code>/cluster/id</code> znode during startup. If the znode does not exist, the broker generates a new cluster id and creates the znode with this cluster id.
-</p>
-
-<h4><a id="impl_brokerregistration" href="#impl_brokerregistration">Broker node registration</a></h4>
-
-<p>
-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.
-</p>
-
-<h4><a id="impl_consumerregistration" href="#impl_consumerregistration">Consumer registration algorithm</a></h4>
-
-<p>
-When a consumer starts, it does the following:
-<ol>
-   <li> Register itself in the consumer id registry under its group.
-   </li>
-   <li> 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.)
-   </li>
-   <li> 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.) </li>
-   <li> 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.)</li>
-   <li> Force itself to rebalance within in its consumer group.
-   </li>
-</ol>
-</p>
-
-<h4><a id="impl_consumerrebalance" href="#impl_consumerrebalance">Consumer rebalancing algorithm</a></h4>
-<p>
-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.
-</p>
-<p>
-Each consumer does the following during rebalancing:
-</p>
-<pre>
-   1. For each topic T that C<sub>i</sub> subscribes to
-   2.   let P<sub>T</sub> be all partitions producing topic T
-   3.   let C<sub>G</sub> be all consumers in the same group as C<sub>i</sub> that consume topic T
-   4.   sort P<sub>T</sub> (so partitions on the same broker are clustered together)
-   5.   sort C<sub>G</sub>
-   6.   let i be the index position of C<sub>i</sub> in C<sub>G</sub> and let N = size(P<sub>T</sub>)/size(C<sub>G</sub>)
-   7.   assign partitions from i*N to (i+1)*N - 1 to consumer C<sub>i</sub>
-   8.   remove current entries owned by C<sub>i</sub> 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)
-</pre>
-<p>
-When rebalancing is triggered at one consumer, rebalancing should be triggered in other consumers within the same group about the same time.
-</p>
+    * 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&lt;KafkaStream&gt; createMessageStreamsByFilter(
+        TopicFilter topicFilter, int numStreams);
+
+    /* Commit the offsets of all messages consumed so far. */
+    public commitOffsets()
+
+    /* Shut down the connector */
+    public shutdown()
+    }
+    </pre>
+    <p>
+    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.
+    </p>
+    <p>
+    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).
+    </p>
+
+    <h3><a id="networklayer" href="#networklayer">5.2 Network Layer</a></h3>
+    <p>
+    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 <code>MessageSet</code> interface a <code>writeTo</code> method. This allows the file-backed message set to use the more efficient <code>transferTo</code> implementation instead of an in-process buffered write. The threading model is a single acceptor thread and <i>N</i> processor threads which handle a fixed number of connections each. This design has been pretty thoroughly tested <a href="http://sna-projects.com/blog/2009/08/introducing-the-nio-socketserver-implementation">elsewhere</a> 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.
+    </p>
+    <h3><a id="messages" href="#messages">5.3 Messages</a></h3>
+    <p>
+    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:
+    <ul>
+        <li> A CRC32 checksum to detect corruption or truncation. <li/>
+        <li> A format version. </li>
+        <li> An attributes identifier </li>
+        <li> A timestamp </li>
+    </ul>
+    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 <code>MessageSet</code> interface is simply an iterator over messages with specialized methods for bulk reading and writing to an NIO <code>Channel</code>.
+
+    <h3><a id="messageformat" href="#messageformat">5.4 Message Format</a></h3>
+
+    <pre>
+        /**
+        * 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
+        */
+    </pre>
+    </p>
+    <h3><a id="log" href="#log">5.5 Log</a></h3>
+    <p>
+    A log for a topic named "my_topic" with two partitions consists of two directories (namely <code>my_topic_0</code> and <code>my_topic_1</code>) 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 <i>N</i> storing the message length which is followed by the <i>N</i> message bytes. Each message is uniquely identified by a 64-bit integer <i>offset</i> 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 <i>S</i> bytes from the previous file where <i>S</i> is the max log file size given in the configuration.
+    </p>
+    <p>
+    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:
+    </p>
+    <pre>
+    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
+    </pre>
+    <p>
+    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&mdash;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.
+    </p>
+    <img class="centered" src="/{{version}}/images/kafka_log.png">
+    <h4><a id="impl_writes" href="#impl_writes">Writes</a></h4>
+    <p>
+    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: <i>M</i>, which gives the number of messages to write before forcing the OS to flush the file to disk, and <i>S</i>, which gives a number of seconds after which a flush is forced. This gives a durability guarantee of losing at most <i>M</i> messages or <i>S</i> seconds of data in the event of a system crash.
+    </p>
+    <h4><a id="impl_reads" href="#impl_reads">Reads</a></h4>
+    <p>
+    Reads are done by giving the 64-bit logical offset of a message and an <i>S</i>-byte max chunk size. This will return an iterator over the messages contained in the <i>S</i>-byte buffer. <i>S</i> 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.
+    </p>
+    <p>
+    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.
+    </p>
+    <p>
+    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.
+    </p>
+
+    <p> The following is the format of the results sent to the consumer.
+
+    <pre>
+    MessageSetSend (fetch result)
+
+    total length     : 4 bytes
+    error code       : 2 bytes
+    message 1        : x bytes
+    ...
+    message n        : x bytes
+    </pre>
+
+    <pre>
+    MultiMessageSetSend (multiFetch result)
+
+    total length       : 4 bytes
+    error code         : 2 bytes
+    messageSetSend 1
+    ...
+    messageSetSend n
+    </pre>
+    <h4><a id="impl_deletes" href="#impl_deletes">Deletes</a></h4>
+    <p>
+    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 <i>N</i> days ago, though a policy which retained the last <i>N</i> 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.
+    </p>
+    <h4><a id="impl_guarantees" href="#impl_guarantees">Guarantees</a></h4>
+    <p>
+    The log provides a configuration parameter <i>M</i> 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.
+    </p>
+    <p>
+    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).
+    </p>
+
+    <h3><a id="distributionimpl" href="#distributionimpl">5.6 Distribution</a></h3>
+    <h4><a id="impl_offsettracking" href="#impl_offsettracking">Consumer Offset Tracking</a></h4>
+    <p>
+    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 <i>offset manager</i>. 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 wi
 ll 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 <a href="https://cwiki.apache.org/confluence/display/KAFKA/Committing+and+fetching+consumer+offsets+in+Kafka">code samples that explain how to issue OffsetCommitRequest and OffsetFetchRequest</a>.
+    </p>
+
+    <p>
+    When the offset manager receives an OffsetCommitRequest, it appends the request to a special <a href="#compaction">compacted</a> Kafka topic named <i>__consumer_offsets</i>. 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.
+    </p>
+
+    <p>
+    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.)
+    </p>
+
+    <h5><a id="offsetmigration" href="#offsetmigration">Migrating offsets from ZooKeeper to Kafka</a></h5>
+    <p>
+    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:
+    <ol>
+    <li>Set <code>offsets.storage=kafka</code> and <code>dual.commit.enabled=true</code> in your consumer config.
+    </li>
+    <li>Do a rolling bounce of your consumers and then verify that your consumers are healthy.
+    </li>
+    <li>Set <code>dual.commit.enabled=false</code> in your consumer config.
+    </li>
+    <li>Do a rolling bounce of your consumers and then verify that your consumers are healthy.
+    </li>
+    </ol>
+    A roll-back (i.e., migrating from Kafka back to ZooKeeper) can also be performed using the above steps if you set <code>offsets.storage=zookeeper</code>.
+    </p>
+
+    <h4><a id="impl_zookeeper" href="#impl_zookeeper">ZooKeeper Directories</a></h4>
+    <p>
+    The following gives the ZooKeeper structures and algorithms used for co-ordination between consumers and brokers.
+    </p>
+
+    <h4><a id="impl_zknotation" href="#impl_zknotation">Notation</a></h4>
+    <p>
+    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".
+    </p>
+
+    <h4><a id="impl_zkbroker" href="#impl_zkbroker">Broker Node Registry</a></h4>
+    <pre>
+    /brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)
+    </pre>
+    <p>
+    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.
+    </p>
+    <p>
+    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).
+    </p>
+    <h4><a id="impl_zktopic" href="#impl_zktopic">Broker Topic Registry</a></h4>
+    <pre>
+    /brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)
+    </pre>
+
+    <p>
+    Each broker registers itself under the topics it maintains and stores the number of partitions for that topic.
+    </p>
+
+    <h4><a id="impl_zkconsumers" href="#impl_zkconsumers">Consumers and Consumer Groups</a></h4>
+    <p>
+    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 <code>offsets.storage=zookeeper</code>. However, this offset storage mechanism will be deprecated in a future release. Therefore, it is recommended to <a href="#offsetmigration">migrate offsets storage to Kafka</a>.
+    </p>
+
+    <p>
+    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.
+    </p>
+
+    <p>
+    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.
+    </p>
+
+    <h4><a id="impl_zkconsumerid" href="#impl_zkconsumerid">Consumer Id Registry</a></h4>
+    <p>
+    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.
+    <pre>
+    /consumers/[group_id]/ids/[consumer_id] --> {"version":...,"subscription":{...:...},"pattern":...,"timestamp":...} (ephemeral node)
+    </pre>
+    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 &lt;topic, #streams&gt;. 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.
+    </p>
+
+    <h4><a id="impl_zkconsumeroffsets" href="#impl_zkconsumeroffsets">Consumer Offsets</a></h4>
+    <p>
+    Consumers track the maximum offset they have consumed in each partition. This value is stored in a ZooKeeper directory if <code>offsets.storage=zookeeper</code>.
+    </p>
+    <pre>
+    /consumers/[group_id]/offsets/[topic]/[partition_id] --> offset_counter_value (persistent node)
+    </pre>
+
+    <h4><a id="impl_zkowner" href="#impl_zkowner">Partition Owner registry</a></h4>
+
+    <p>
+    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.
+    </p>
+
+    <pre>
+    /consumers/[group_id]/owners/[topic]/[partition_id] --> consumer_node_id (ephemeral node)
+    </pre>
+
+    <h4><a id="impl_clusterid" href="#impl_clusterid">Cluster Id</a></h4>
+
+    <p>
+        The cluster id is a unique and immutable identifier assigned to a Kafka cluster. The cluster id can have a maximum of 22 characters and the allowed characters are defined by the regular expression [a-zA-Z0-9_\-]+, which corresponds to the characters used by the URL-safe Base64 variant with no padding. Conceptually, it is auto-generated when a cluster is started for the first time.
+    </p>
+    <p>
+        Implementation-wise, it is generated when a broker with version 0.10.1 or later is successfully started for the first time. The broker tries to get the cluster id from the <code>/cluster/id</code> znode during startup. If the znode does not exist, the broker generates a new cluster id and creates the znode with this cluster id.
+    </p>
+
+    <h4><a id="impl_brokerregistration" href="#impl_brokerregistration">Broker node registration</a></h4>
+
+    <p>
+    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.
+    </p>
+
+    <h4><a id="impl_consumerregistration" href="#impl_consumerregistration">Consumer registration algorithm</a></h4>
+
+    <p>
+    When a consumer starts, it does the following:
+    <ol>
+    <li> Register itself in the consumer id registry under its group.
+    </li>
+    <li> 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.)
+    </li>
+    <li> 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.) </li>
+    <li> 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.)</li>
+    <li> Force itself to rebalance within in its consumer group.
+    </li>
+    </ol>
+    </p>
+
+    <h4><a id="impl_consumerrebalance" href="#impl_consumerrebalance">Consumer rebalancing algorithm</a></h4>
+    <p>
+    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.
+    </p>
+    <p>
+    Each consumer does the following during rebalancing:
+    </p>
+    <pre>
+    1. For each topic T that C<sub>i</sub> subscribes to
+    2.   let P<sub>T</sub> be all partitions producing topic T
+    3.   let C<sub>G</sub> be all consumers in the same group as C<sub>i</sub> that consume topic T
+    4.   sort P<sub>T</sub> (so partitions on the same broker are clustered together)
+    5.   sort C<sub>G</sub>
+    6.   let i be the index position of C<sub>i</sub> in C<sub>G</sub> and let N = size(P<sub>T</sub>)/size(C<sub>G</sub>)
+    7.   assign partitions from i*N to (i+1)*N - 1 to consumer C<sub>i</sub>
+    8.   remove current entries owned by C<sub>i</sub> 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)
+    </pre>
+    <p>
+    When rebalancing is triggered at one consumer, rebalancing should be triggered in other consumers within the same group about the same time.
+    </p>
+</script>
+
+<div class="p-implementation"></div>


[2/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/security.html
----------------------------------------------------------------------
diff --git a/docs/security.html b/docs/security.html
index f58179f..1f2e6f5 100644
--- a/docs/security.html
+++ b/docs/security.html
@@ -15,732 +15,736 @@
  limitations under the License.
 -->
 
-<h3><a id="security_overview" href="#security_overview">7.1 Security Overview</a></h3>
-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:
-<ol>
-    <li>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.</li>
-    <li>Authentication of connections from brokers to ZooKeeper</li>
-    <li>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.)</li>
-    <li>Authorization of read / write operations by clients</li>
-    <li>Authorization is pluggable and integration with external authorization services is supported</li>
-</ol>
-
-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.
-
-<h3><a id="security_ssl" href="#security_ssl">7.2 Encryption and Authentication using SSL</a></h3>
-Apache Kafka allows clients to connect over SSL. By default, SSL is disabled but can be turned on as needed.
-
-<ol>
-    <li><h4><a id="security_ssl_key" href="#security_ssl_key">Generate SSL key and certificate for each Kafka broker</a></h4>
-        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.
-        <pre>
-        keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey</pre>
+<script id="security-template" type="text/x-handlebars-template">
+    <h3><a id="security_overview" href="#security_overview">7.1 Security Overview</a></h3>
+    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:
+    <ol>
+        <li>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.</li>
+        <li>Authentication of connections from brokers to ZooKeeper</li>
+        <li>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.)</li>
+        <li>Authorization of read / write operations by clients</li>
+        <li>Authorization is pluggable and integration with external authorization services is supported</li>
+    </ol>
 
-        You need to specify two parameters in the above command:
-        <ol>
-            <li>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.</li>
-            <li>validity: the valid time of the certificate in days.</li>
-        </ol>
-        <br>
-	Note: By default the property <code>ssl.endpoint.identification.algorithm</code> is not defined, so hostname verification is not performed. In order to enable hostname verification, set the following property:
-
-	<pre>	ssl.endpoint.identification.algorithm=HTTPS </pre>
-
-	Once enabled, clients will verify the server's fully qualified domain name (FQDN) against one of the following two fields:
-	<ol>
-		<li>Common Name (CN)
-		<li>Subject Alternative Name (SAN)
-	</ol>
-	<br>
-	Both fields are valid, RFC-2818 recommends the use of SAN however. SAN is also more flexible, allowing for multiple DNS entries to be declared. Another advantage is that the CN can be set to a more meaningful value for authorization purposes. To add a SAN field  append the following argument <code> -ext SAN=DNS:{FQDN} </code> to the keytool command:
-	<pre>
-	keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -ext SAN=DNS:{FQDN}
-	</pre>
-	The following command can be run afterwards to verify the contents of the generated certificate:
-	<pre>
-	keytool -list -v -keystore server.keystore.jks
-	</pre>
-    </li>
-    <li><h4><a id="security_ssl_ca" href="#security_ssl_ca">Creating your own CA</a></h4>
-        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.<p>
-        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\u2014the 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.
-        <pre>
-        openssl req <b>-new</b> -x509 -keyout ca-key -out ca-cert -days 365</pre>
+    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 generated CA is simply a public-private key pair and certificate, and it is intended to sign other certificates.<br>
+    The guides below explain how to configure and use the security features in both clients and brokers.
 
-        The next step is to add the generated CA to the **clients' truststore** so that the clients can trust this CA:
-        <pre>
-        keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert</pre>
+    <h3><a id="security_ssl" href="#security_ssl">7.2 Encryption and Authentication using SSL</a></h3>
+    Apache Kafka allows clients to connect over SSL. By default, SSL is disabled but can be turned on as needed.
 
-        <b>Note:</b> If you configure the Kafka brokers to require client authentication by setting ssl.client.auth to be "requested" or "required" on the <a href="#config_broker">Kafka brokers config</a> 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.
-        <pre>
-        keytool -keystore server.truststore.jks -alias CARoot <b>-import</b> -file ca-cert</pre>
+    <ol>
+        <li><h4><a id="security_ssl_key" href="#security_ssl_key">Generate SSL key and certificate for each Kafka broker</a></h4>
+            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.
+            <pre>
+            keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey</pre>
 
-        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.</li>
+            You need to specify two parameters in the above command:
+            <ol>
+                <li>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.</li>
+                <li>validity: the valid time of the certificate in days.</li>
+            </ol>
+            <br>
+        Note: By default the property <code>ssl.endpoint.identification.algorithm</code> is not defined, so hostname verification is not performed. In order to enable hostname verification, set the following property:
 
-    <li><h4><a id="security_ssl_signing" href="#security_ssl_signing">Signing the certificate</a></h4>
-        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:
-        <pre>
-        keytool -keystore server.keystore.jks -alias localhost -certreq -file cert-file</pre>
+        <pre>	ssl.endpoint.identification.algorithm=HTTPS </pre>
 
-        Then sign it with the CA:
+        Once enabled, clients will verify the server's fully qualified domain name (FQDN) against one of the following two fields:
+        <ol>
+            <li>Common Name (CN)
+            <li>Subject Alternative Name (SAN)
+        </ol>
+        <br>
+        Both fields are valid, RFC-2818 recommends the use of SAN however. SAN is also more flexible, allowing for multiple DNS entries to be declared. Another advantage is that the CN can be set to a more meaningful value for authorization purposes. To add a SAN field  append the following argument <code> -ext SAN=DNS:{FQDN} </code> to the keytool command:
         <pre>
-        openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed -days {validity} -CAcreateserial -passin pass:{ca-password}</pre>
-
-        Finally, you need to import both the certificate of the CA and the signed certificate into the keystore:
+        keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -ext SAN=DNS:{FQDN}
+        </pre>
+        The following command can be run afterwards to verify the contents of the generated certificate:
         <pre>
-        keytool -keystore server.keystore.jks -alias CARoot -import -file ca-cert
-        keytool -keystore server.keystore.jks -alias localhost -import -file cert-signed</pre>
+        keytool -list -v -keystore server.keystore.jks
+        </pre>
+        </li>
+        <li><h4><a id="security_ssl_ca" href="#security_ssl_ca">Creating your own CA</a></h4>
+            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.<p>
+            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\u2014the 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.
+            <pre>
+            openssl req <b>-new</b> -x509 -keyout ca-key -out ca-cert -days 365</pre>
 
-        The definitions of the parameters are the following:
-        <ol>
-            <li>keystore: the location of the keystore</li>
-            <li>ca-cert: the certificate of the CA</li>
-            <li>ca-key: the private key of the CA</li>
-            <li>ca-password: the passphrase of the CA</li>
-            <li>cert-file: the exported, unsigned certificate of the server</li>
-            <li>cert-signed: the signed certificate of the server</li>
-        </ol>
+            The generated CA is simply a public-private key pair and certificate, and it is intended to sign other certificates.<br>
 
-        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.
+            The next step is to add the generated CA to the **clients' truststore** so that the clients can trust this CA:
             <pre>
-        #!/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</pre></li>
-    <li><h4><a id="security_configbroker" href="#security_configbroker">Configuring Kafka Brokers</a></h4>
-        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:
-        <pre>listeners</pre>
-
-        If SSL is not enabled for inter-broker communication (see below for how to enable it), both PLAINTEXT and SSL ports will be necessary.
-        <pre>
-        listeners=PLAINTEXT://host.name:port,SSL://host.name:port</pre>
+            keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert</pre>
 
-        Following SSL configs are needed on the broker side
-        <pre>
-        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</pre>
+            <b>Note:</b> If you configure the Kafka brokers to require client authentication by setting ssl.client.auth to be "requested" or "required" on the <a href="#config_broker">Kafka brokers config</a> 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.
+            <pre>
+            keytool -keystore server.truststore.jks -alias CARoot <b>-import</b> -file ca-cert</pre>
 
-        Optional settings that are worth considering:
-        <ol>
-            <li>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.)</li>
-            <li>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)</li>
-            <li>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)</li>
-            <li>ssl.keystore.type=JKS</li>
-            <li>ssl.truststore.type=JKS</li>
-            <li>ssl.secure.random.implementation=SHA1PRNG</li>
-        </ol>
-        If you want to enable SSL for inter-broker communication, add the following to the broker properties file (it defaults to PLAINTEXT)
-        <pre>
-        security.inter.broker.protocol=SSL</pre>
+            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.</li>
 
-        <p>
-        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 <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">JCE Unlimited Strength Jurisdiction Policy Files</a> must be obtained and installed in the JDK/JRE. See the
-        <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html">JCA Providers Documentation</a> for more information.
-        </p>
+        <li><h4><a id="security_ssl_signing" href="#security_ssl_signing">Signing the certificate</a></h4>
+            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:
+            <pre>
+            keytool -keystore server.keystore.jks -alias localhost -certreq -file cert-file</pre>
 
-        <p>
-        The JRE/JDK will have a default pseudo-random number generator (PRNG) that is used for cryptography operations, so it is not required to configure the
-        implementation used with the <pre>ssl.secure.random.implementation</pre>. However, there are performance issues with some implementations (notably, the
-        default chosen on Linux systems, <pre>NativePRNG</pre>, utilizes a global lock). In cases where performance of SSL connections becomes an issue,
-        consider explicitly setting the implementation to be used. The <pre>SHA1PRNG</pre> implementation is non-blocking, and has shown very good performance
-        characteristics under heavy load (50 MB/sec of produced messages, plus replication traffic, per-broker).
-        </p>
+            Then sign it with the CA:
+            <pre>
+            openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed -days {validity} -CAcreateserial -passin pass:{ca-password}</pre>
 
-        Once you start the broker you should be able to see in the server.log
-        <pre>
-        with addresses: PLAINTEXT -> EndPoint(192.168.64.1,9092,PLAINTEXT),SSL -> EndPoint(192.168.64.1,9093,SSL)</pre>
+            Finally, you need to import both the certificate of the CA and the signed certificate into the keystore:
+            <pre>
+            keytool -keystore server.keystore.jks -alias CARoot -import -file ca-cert
+            keytool -keystore server.keystore.jks -alias localhost -import -file cert-signed</pre>
 
-        To check quickly if  the server keystore and truststore are setup properly you can run the following command
-        <pre>openssl s_client -debug -connect localhost:9093 -tls1</pre> (Note: TLSv1 should be listed under ssl.enabled.protocols)<br>
-        In the output of this command you should see server's certificate:
-        <pre>
-        -----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</pre>
-        If the certificate does not show up or if there are any other error messages then your keystore is not setup properly.</li>
-
-    <li><h4><a id="security_configclients" href="#security_configclients">Configuring Kafka Clients</a></h4>
-        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.<br>
-        If client authentication is not required in the broker, then the following is a minimal configuration example:
-        <pre>
-        security.protocol=SSL
-        ssl.truststore.location=/var/private/ssl/kafka.client.truststore.jks
-        ssl.truststore.password=test1234</pre>
+            The definitions of the parameters are the following:
+            <ol>
+                <li>keystore: the location of the keystore</li>
+                <li>ca-cert: the certificate of the CA</li>
+                <li>ca-key: the private key of the CA</li>
+                <li>ca-password: the passphrase of the CA</li>
+                <li>cert-file: the exported, unsigned certificate of the server</li>
+                <li>cert-signed: the signed certificate of the server</li>
+            </ol>
 
-        If client authentication is required, then a keystore must be created like in step 1 and the following must also be configured:
-        <pre>
-        ssl.keystore.location=/var/private/ssl/kafka.client.keystore.jks
-        ssl.keystore.password=test1234
-        ssl.key.password=test1234</pre>
-        Other configuration settings that may also be needed depending on our requirements and the broker configuration:
+            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.
+                <pre>
+            #!/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</pre></li>
+        <li><h4><a id="security_configbroker" href="#security_configbroker">Configuring Kafka Brokers</a></h4>
+            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:
+            <pre>listeners</pre>
+
+            If SSL is not enabled for inter-broker communication (see below for how to enable it), both PLAINTEXT and SSL ports will be necessary.
+            <pre>
+            listeners=PLAINTEXT://host.name:port,SSL://host.name:port</pre>
+
+            Following SSL configs are needed on the broker side
+            <pre>
+            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</pre>
+
+            Optional settings that are worth considering:
             <ol>
-                <li>ssl.provider (Optional). The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.</li>
-                <li>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.</li>
-                <li>ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1. It should list at least one of the protocols configured on the broker side</li>
-                <li>ssl.truststore.type=JKS</li>
+                <li>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.)</li>
+                <li>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)</li>
+                <li>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)</li>
                 <li>ssl.keystore.type=JKS</li>
+                <li>ssl.truststore.type=JKS</li>
+                <li>ssl.secure.random.implementation=SHA1PRNG</li>
             </ol>
-<br>
-        Examples using console-producer and console-consumer:
-        <pre>
-        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 --consumer.config client-ssl.properties</pre>
-    </li>
-</ol>
-<h3><a id="security_sasl" href="#security_sasl">7.3 Authentication using SASL</a></h3>
+            If you want to enable SSL for inter-broker communication, add the following to the broker properties file (it defaults to PLAINTEXT)
+            <pre>
+            security.inter.broker.protocol=SSL</pre>
+
+            <p>
+            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 <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">JCE Unlimited Strength Jurisdiction Policy Files</a> must be obtained and installed in the JDK/JRE. See the
+            <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html">JCA Providers Documentation</a> for more information.
+            </p>
+
+            <p>
+            The JRE/JDK will have a default pseudo-random number generator (PRNG) that is used for cryptography operations, so it is not required to configure the
+            implementation used with the <pre>ssl.secure.random.implementation</pre>. However, there are performance issues with some implementations (notably, the
+            default chosen on Linux systems, <pre>NativePRNG</pre>, utilizes a global lock). In cases where performance of SSL connections becomes an issue,
+            consider explicitly setting the implementation to be used. The <pre>SHA1PRNG</pre> implementation is non-blocking, and has shown very good performance
+            characteristics under heavy load (50 MB/sec of produced messages, plus replication traffic, per-broker).
+            </p>
+
+            Once you start the broker you should be able to see in the server.log
+            <pre>
+            with addresses: PLAINTEXT -> EndPoint(192.168.64.1,9092,PLAINTEXT),SSL -> EndPoint(192.168.64.1,9093,SSL)</pre>
 
-<ol>
-  <li><h4><a id="security_sasl_brokerconfig"
-    href="#security_sasl_brokerconfig">SASL configuration for Kafka brokers</a></h4>
-    <ol>
-      <li>Select one or more supported mechanisms to enable in the broker. <tt>GSSAPI</tt>
-        and <tt>PLAIN</tt> are the mechanisms currently supported in Kafka.</li>
-      <li>Add a JAAS config file for the selected mechanisms as described in the examples
-        for setting up <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
-        or <a href="#security_sasl_plain_brokerconfig">PLAIN</a>.</li>
-      <li>Pass the JAAS config file location as JVM parameter to each Kafka broker.
-        For example:
-        <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre></li>
-      <li>Configure a SASL port in server.properties, by adding at least one of
-        SASL_PLAINTEXT or SASL_SSL to the <i>listeners</i> parameter, which
-        contains one or more comma-separated values:
-        <pre>    listeners=SASL_PLAINTEXT://host.name:port</pre>
-        If SASL_SSL is used, then <a href="#security_ssl">SSL must also be
-        configured</a>. 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:
-        <pre>    security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)</pre></li>
-      <li>Enable one or more SASL mechanisms in server.properties:
-          <pre>    sasl.enabled.mechanisms=GSSAPI (,PLAIN)</pre></li>
-      <li>Configure the SASL mechanism for inter-broker communication in server.properties
-        if using SASL for inter-broker communication:
-        <pre>    sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)</pre></li>
-      <li>Follow the steps in <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
-        or <a href="#security_sasl_plain_brokerconfig">PLAIN</a> to configure SASL
-        for the enabled mechanisms. To enable multiple mechanisms in the broker, follow
-        the steps <a href="#security_sasl_multimechanism">here</a>.</li>
-      <u><a id="security_sasl_brokernotes" href="#security_sasl_brokernotes">Important notes:</a></u>
-      <ol>
-        <li><tt>KafkaServer</tt> 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.</li>
-        <li><tt>Client</tt> 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 <tt>zookeeper.sasl.client</tt> to the appropriate
-          name (<i>e.g.</i>, <tt>-Dzookeeper.sasl.client=ZkClient</tt>).</li>
-        <li>ZooKeeper uses "zookeeper" as the service name by default. If you
-          want to change this, set the system property
-          <tt>zookeeper.sasl.client.username</tt> to the appropriate name
-          (<i>e.g.</i>, <tt>-Dzookeeper.sasl.client.username=zk</tt>).</li>
-      </ol>
-    </ol>
-  </li>
-  <li><h4><a id="security_sasl_clientconfig"
-    href="#security_sasl_clientconfig">SASL configuration for Kafka clients</a></h4>
-    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:
-    <ol>
-      <li>Select a SASL mechanism for authentication.</li>
-      <li>Add a JAAS config file for the selected mechanism as described in the examples
-        for setting up <a href="#security_sasl_kerberos_clientconfig">GSSAPI (Kerberos)</a>
-        or <a href="#security_sasl_plain_clientconfig">PLAIN</a>. <tt>KafkaClient</tt> is the
-        section name in the JAAS file used by Kafka clients.</li>
-      <li>Pass the JAAS config file location as JVM parameter to each client JVM. For example:
-        <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf</pre></li>
-      <li>Configure the following properties in producer.properties or
-        consumer.properties:
-        <pre>    security.protocol=SASL_PLAINTEXT (or SASL_SSL)
-    sasl.mechanism=GSSAPI (or PLAIN)</pre></li>
-      <li>Follow the steps in <a href="#security_sasl_kerberos_clientconfig">GSSAPI (Kerberos)</a>
-        or <a href="#security_sasl_plain_clientconfig">PLAIN</a> to configure SASL
-        for the selected mechanism.</li>
-    </ol>
-  </li>
-  <li><h4><a id="security_sasl_kerberos" href="#security_sasl_kerberos">Authentication using SASL/Kerberos</a></h4>
-    <ol>
-      <li><h5><a id="security_sasl_kerberos_prereq" href="#security_sasl_kerberos_prereq">Prerequisites</a></h5>
-      <ol>
-          <li><b>Kerberos</b><br>
-          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 (<a href="https://help.ubuntu.com/community/Kerberos">Ubuntu</a>, <a href="https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Managing_Smart_Cards/installing-kerberos.html">Redhat</a>). 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.</li>
-          <li><b>Create Kerberos Principals</b><br>
-          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).</br>
-          If you have installed your own Kerberos, you will need to create these principals yourself using the following commands:
+            To check quickly if  the server keystore and truststore are setup properly you can run the following command
+            <pre>openssl s_client -debug -connect localhost:9093 -tls1</pre> (Note: TLSv1 should be listed under ssl.enabled.protocols)<br>
+            In the output of this command you should see server's certificate:
             <pre>
-    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}"</pre></li>
-          <li><b>Make sure all hosts can be reachable using hostnames</b> - it is a Kerberos requirement that all your hosts can be resolved with their FQDNs.</li>
-      </ol>
-      <li><h5><a id="security_sasl_kerberos_brokerconfig" href="#security_sasl_kerberos_brokerconfig">Configuring Kafka Brokers</a></h5>
-      <ol>
-          <li>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):
-          <pre>
-    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";
-    };</pre>
-
-          </li>
-          <tt>KafkaServer</tt> 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 <a href="#security_sasl_brokernotes">notes</a> for more details on Zookeeper SASL configuration.
-          <li>Pass the JAAS and optionally the krb5 file locations as JVM parameters to each Kafka broker (see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/KerberosReq.html">here</a> for more details): 
-            <pre>    -Djava.security.krb5.conf=/etc/kafka/krb5.conf
-    -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre>
-          </li>
-          <li>Make sure the keytabs configured in the JAAS file are readable by the operating system user who is starting kafka broker.</li>
-          <li>Configure SASL port and SASL mechanisms in server.properties as described <a href="#security_sasl_brokerconfig">here</a>.</pre> For example:
-          <pre>    listeners=SASL_PLAINTEXT://host.name:port
-    security.inter.broker.protocol=SASL_PLAINTEXT
-    sasl.mechanism.inter.broker.protocol=GSSAPI
-    sasl.enabled.mechanisms=GSSAPI
-          </pre>
-          </li>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: 
-          <pre>    sasl.kerberos.service.name=kafka</pre>
-
-      </ol></li>
-      <li><h5><a id="security_sasl_kerberos_clientconfig" href="#security_kerberos_sasl_clientconfig">Configuring Kafka Clients</a></h5>
-          To configure SASL authentication on the clients:
-          <ol>
-              <li>
-                  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):
-              <pre>
-    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";
-    };</pre>
+            -----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</pre>
+            If the certificate does not show up or if there are any other error messages then your keystore is not setup properly.</li>
+
+        <li><h4><a id="security_configclients" href="#security_configclients">Configuring Kafka Clients</a></h4>
+            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.<br>
+            If client authentication is not required in the broker, then the following is a minimal configuration example:
+            <pre>
+            security.protocol=SSL
+            ssl.truststore.location=/var/private/ssl/kafka.client.truststore.jks
+            ssl.truststore.password=test1234</pre>
 
-              For command-line utilities like kafka-console-consumer or kafka-console-producer, kinit can be used along with "useTicketCache=true" as in:
-              <pre>
-    KafkaClient {
-        com.sun.security.auth.module.Krb5LoginModule required
-        useTicketCache=true;
-    };</pre>
-              </li>
-              <li>Pass the JAAS and optionally krb5 file locations as JVM parameters to each client JVM (see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/KerberosReq.html">here</a> for more details): 
-              <pre>    -Djava.security.krb5.conf=/etc/kafka/krb5.conf
-    -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf</pre></li>
-              <li>Make sure the keytabs configured in the kafka_client_jaas.conf are readable by the operating system user who is starting kafka client.</li>
-              <li>Configure the following properties in producer.properties or consumer.properties: 
-              <pre>    security.protocol=SASL_PLAINTEXT (or SASL_SSL)
-    sasl.mechanism=GSSAPI
-    sasl.kerberos.service.name=kafka</pre></li>
-          </ol>
-      </li>
+            If client authentication is required, then a keystore must be created like in step 1 and the following must also be configured:
+            <pre>
+            ssl.keystore.location=/var/private/ssl/kafka.client.keystore.jks
+            ssl.keystore.password=test1234
+            ssl.key.password=test1234</pre>
+            Other configuration settings that may also be needed depending on our requirements and the broker configuration:
+                <ol>
+                    <li>ssl.provider (Optional). The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.</li>
+                    <li>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.</li>
+                    <li>ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1. It should list at least one of the protocols configured on the broker side</li>
+                    <li>ssl.truststore.type=JKS</li>
+                    <li>ssl.keystore.type=JKS</li>
+                </ol>
+    <br>
+            Examples using console-producer and console-consumer:
+            <pre>
+            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 --consumer.config client-ssl.properties</pre>
+        </li>
     </ol>
-  </li>
-      
-  <li><h4><a id="security_sasl_plain" href="#security_sasl_plain">Authentication using SASL/PLAIN</a></h4>
-    <p>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 <a href="#security_sasl_plain_production">here</a>.</p>
-       The username is used as the authenticated <code>Principal</code> for configuration of ACLs etc.
+    <h3><a id="security_sasl" href="#security_sasl">7.3 Authentication using SASL</a></h3>
+
     <ol>
-      <li><h5><a id="security_sasl_plain_brokerconfig" href="#security_sasl_plain_brokerconfig">Configuring Kafka Brokers</a></h5>
+    <li><h4><a id="security_sasl_brokerconfig"
+        href="#security_sasl_brokerconfig">SASL configuration for Kafka brokers</a></h4>
         <ol>
-          <li>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:
-            <pre>
-    KafkaServer {
-        org.apache.kafka.common.security.plain.PlainLoginModule required
-        username="admin"
-        password="admin-secret"
-        user_admin="admin-secret"
-        user_alice="alice-secret";
-    };</pre>
-            This configuration defines two users (<i>admin</i> and <i>alice</i>). The properties <tt>username</tt> and <tt>password</tt>
-            in the <tt>KafkaServer</tt> section are used by the broker to initiate connections to other brokers. In this example,
-            <i>admin</i> is the user for inter-broker communication. The set of properties <tt>user_<i>userName</i></tt> 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.</li>
-          <li>Pass the JAAS config file location as JVM parameter to each Kafka broker:
-              <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre></li>
-          <li>Configure SASL port and SASL mechanisms in server.properties as described <a href="#security_sasl_brokerconfig">here</a>.</pre> For example:
-            <pre>    listeners=SASL_SSL://host.name:port
-    security.inter.broker.protocol=SASL_SSL
-    sasl.mechanism.inter.broker.protocol=PLAIN
-    sasl.enabled.mechanisms=PLAIN</pre></li>
+        <li>Select one or more supported mechanisms to enable in the broker. <tt>GSSAPI</tt>
+            and <tt>PLAIN</tt> are the mechanisms currently supported in Kafka.</li>
+        <li>Add a JAAS config file for the selected mechanisms as described in the examples
+            for setting up <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
+            or <a href="#security_sasl_plain_brokerconfig">PLAIN</a>.</li>
+        <li>Pass the JAAS config file location as JVM parameter to each Kafka broker.
+            For example:
+            <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre></li>
+        <li>Configure a SASL port in server.properties, by adding at least one of
+            SASL_PLAINTEXT or SASL_SSL to the <i>listeners</i> parameter, which
+            contains one or more comma-separated values:
+            <pre>    listeners=SASL_PLAINTEXT://host.name:port</pre>
+            If SASL_SSL is used, then <a href="#security_ssl">SSL must also be
+            configured</a>. 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:
+            <pre>    security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)</pre></li>
+        <li>Enable one or more SASL mechanisms in server.properties:
+            <pre>    sasl.enabled.mechanisms=GSSAPI (,PLAIN)</pre></li>
+        <li>Configure the SASL mechanism for inter-broker communication in server.properties
+            if using SASL for inter-broker communication:
+            <pre>    sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)</pre></li>
+        <li>Follow the steps in <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
+            or <a href="#security_sasl_plain_brokerconfig">PLAIN</a> to configure SASL
+            for the enabled mechanisms. To enable multiple mechanisms in the broker, follow
+            the steps <a href="#security_sasl_multimechanism">here</a>.</li>
+        <u><a id="security_sasl_brokernotes" href="#security_sasl_brokernotes">Important notes:</a></u>
+        <ol>
+            <li><tt>KafkaServer</tt> 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.</li>
+            <li><tt>Client</tt> 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 <tt>zookeeper.sasl.client</tt> to the appropriate
+            name (<i>e.g.</i>, <tt>-Dzookeeper.sasl.client=ZkClient</tt>).</li>
+            <li>ZooKeeper uses "zookeeper" as the service name by default. If you
+            want to change this, set the system property
+            <tt>zookeeper.sasl.client.username</tt> to the appropriate name
+            (<i>e.g.</i>, <tt>-Dzookeeper.sasl.client.username=zk</tt>).</li>
         </ol>
-      </li>
-
-      <li><h5><a id="security_sasl_plain_clientconfig" href="#security_sasl_plain_clientconfig">Configuring Kafka Clients</a></h5>
-        To configure SASL authentication on the clients:
+        </ol>
+    </li>
+    <li><h4><a id="security_sasl_clientconfig"
+        href="#security_sasl_clientconfig">SASL configuration for Kafka clients</a></h4>
+        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:
         <ol>
-          <li>The <tt>KafkaClient</tt> 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:
-            <pre>
-    KafkaClient {
-        org.apache.kafka.common.security.plain.PlainLoginModule required
-        username="alice"
-        password="alice-secret";
-    };</pre>
-            The properties <tt>username</tt> and <tt>password</tt> in the <tt>KafkaClient</tt> section are used by clients to configure
-            the user for client connections. In this example, clients connect to the broker as user <i>alice</i>.
-          </li>
-          <li>Pass the JAAS config file location as JVM parameter to each client JVM:
+        <li>Select a SASL mechanism for authentication.</li>
+        <li>Add a JAAS config file for the selected mechanism as described in the examples
+            for setting up <a href="#security_sasl_kerberos_clientconfig">GSSAPI (Kerberos)</a>
+            or <a href="#security_sasl_plain_clientconfig">PLAIN</a>. <tt>KafkaClient</tt> is the
+            section name in the JAAS file used by Kafka clients.</li>
+        <li>Pass the JAAS config file location as JVM parameter to each client JVM. For example:
             <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf</pre></li>
-          <li>Configure the following properties in producer.properties or consumer.properties:
-            <pre>    security.protocol=SASL_SSL
-    sasl.mechanism=PLAIN</pre></li>
+        <li>Configure the following properties in producer.properties or
+            consumer.properties:
+            <pre>    security.protocol=SASL_PLAINTEXT (or SASL_SSL)
+        sasl.mechanism=GSSAPI (or PLAIN)</pre></li>
+        <li>Follow the steps in <a href="#security_sasl_kerberos_clientconfig">GSSAPI (Kerberos)</a>
+            or <a href="#security_sasl_plain_clientconfig">PLAIN</a> to configure SASL
+            for the selected mechanism.</li>
         </ol>
-      </li>
-      <li><h5><a id="security_sasl_plain_production" href="#security_sasl_plain_production">Use of SASL/PLAIN in production</a></h5>
-        <ul>
-          <li>SASL/PLAIN should be used only with SSL as transport layer to ensure that clear passwords are not transmitted on the wire without encryption.</li>
-          <li>The default implementation of SASL/PLAIN in Kafka specifies usernames and passwords in the JAAS configuration file as shown
-            <a href="#security_sasl_plain_brokerconfig">here</a>. To avoid storing passwords on disk, you can plug in your own implementation of
-            <code>javax.security.auth.spi.LoginModule</code> 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 <code>Subject</code>. The default implementation
-            <code>org.apache.kafka.common.security.plain.PlainLoginModule</code> can be used as an example.</li>
-          <li>In production systems, external authentication servers may implement password authentication. Kafka brokers can be integrated with these servers by adding
-            your own implementation of <code>javax.security.sasl.SaslServer</code>. The default implementation included in Kafka in the package
-            <code>org.apache.kafka.common.security.plain</code> can be used as an example to get started.
-            <ul>
-              <li>New providers must be installed and registered in the JVM. Providers can be installed by adding provider classes to
-              the normal <tt>CLASSPATH</tt> or bundled as a jar file and added to <tt><i>JAVA_HOME</i>/lib/ext</tt>.</li>
-              <li>Providers can be registered statically by adding a provider to the security properties file
-              <tt><i>JAVA_HOME</i>/lib/security/java.security</tt>.
-              <pre>    security.provider.n=providerClassName</pre>
-              where <i>providerClassName</i> is the fully qualified name of the new provider and <i>n</i> is the preference order with
-              lower numbers indicating higher preference.</li>
-              <li>Alternatively, you can register providers dynamically at runtime by invoking <code>Security.addProvider</code> at the beginning of the client
-              application or in a static initializer in the login module. For example:
-              <pre>    Security.addProvider(new PlainSaslServerProvider());</pre></li>
-              <li>For more details, see <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html">JCA Reference</a>.</li>
-            </ul>
-          </li>
-        </ul>
-      </li>
-    </ol>
-  </li>
-  <li><h4><a id="security_sasl_multimechanism" href="#security_sasl_multimechanism">Enabling multiple SASL mechanisms in a broker</a></h4>
-    <ol>
-      <li>Specify configuration for the login modules of all enabled mechanisms in the <tt>KafkaServer</tt> section of the JAAS config file. For example:
-        <pre>
-    KafkaServer {
+    </li>
+    <li><h4><a id="security_sasl_kerberos" href="#security_sasl_kerberos">Authentication using SASL/Kerberos</a></h4>
+        <ol>
+        <li><h5><a id="security_sasl_kerberos_prereq" href="#security_sasl_kerberos_prereq">Prerequisites</a></h5>
+        <ol>
+            <li><b>Kerberos</b><br>
+            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 (<a href="https://help.ubuntu.com/community/Kerberos">Ubuntu</a>, <a href="https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Managing_Smart_Cards/installing-kerberos.html">Redhat</a>). 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.</li>
+            <li><b>Create Kerberos Principals</b><br>
+            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).</br>
+            If you have installed your own Kerberos, you will need to create these principals yourself using the following commands:
+                <pre>
+        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}"</pre></li>
+            <li><b>Make sure all hosts can be reachable using hostnames</b> - it is a Kerberos requirement that all your hosts can be resolved with their FQDNs.</li>
+        </ol>
+        <li><h5><a id="security_sasl_kerberos_brokerconfig" href="#security_sasl_kerberos_brokerconfig">Configuring Kafka Brokers</a></h5>
+        <ol>
+            <li>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):
+            <pre>
+        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";
+        };</pre>
+
+            </li>
+            <tt>KafkaServer</tt> 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 <a href="#security_sasl_brokernotes">notes</a> for more details on Zookeeper SASL configuration.
+            <li>Pass the JAAS and optionally the krb5 file locations as JVM parameters to each Kafka broker (see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/KerberosReq.html">here</a> for more details): 
+                <pre>    -Djava.security.krb5.conf=/etc/kafka/krb5.conf
+        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre>
+            </li>
+            <li>Make sure the keytabs configured in the JAAS file are readable by the operating system user who is starting kafka broker.</li>
+            <li>Configure SASL port and SASL mechanisms in server.properties as described <a href="#security_sasl_brokerconfig">here</a>.</pre> For example:
+            <pre>    listeners=SASL_PLAINTEXT://host.name:port
+        security.inter.broker.protocol=SASL_PLAINTEXT
+        sasl.mechanism.inter.broker.protocol=GSSAPI
+        sasl.enabled.mechanisms=GSSAPI
+            </pre>
+            </li>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: 
+            <pre>    sasl.kerberos.service.name=kafka</pre>
+
+        </ol></li>
+        <li><h5><a id="security_sasl_kerberos_clientconfig" href="#security_kerberos_sasl_clientconfig">Configuring Kafka Clients</a></h5>
+            To configure SASL authentication on the clients:
+            <ol>
+                <li>
+                    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):
+                <pre>
+        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";
+        };</pre>
+
+                For command-line utilities like kafka-console-consumer or kafka-console-producer, kinit can be used along with "useTicketCache=true" as in:
+                <pre>
+        KafkaClient {
+            com.sun.security.auth.module.Krb5LoginModule required
+            useTicketCache=true;
+        };</pre>
+                </li>
+                <li>Pass the JAAS and optionally krb5 file locations as JVM parameters to each client JVM (see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/KerberosReq.html">here</a> for more details): 
+                <pre>    -Djava.security.krb5.conf=/etc/kafka/krb5.conf
+        -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf</pre></li>
+                <li>Make sure the keytabs configured in the kafka_client_jaas.conf are readable by the operating system user who is starting kafka client.</li>
+                <li>Configure the following properties in producer.properties or consumer.properties: 
+                <pre>    security.protocol=SASL_PLAINTEXT (or SASL_SSL)
+        sasl.mechanism=GSSAPI
+        sasl.kerberos.service.name=kafka</pre></li>
+            </ol>
+        </li>
+        </ol>
+    </li>
+        
+    <li><h4><a id="security_sasl_plain" href="#security_sasl_plain">Authentication using SASL/PLAIN</a></h4>
+        <p>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 <a href="#security_sasl_plain_production">here</a>.</p>
+        The username is used as the authenticated <code>Principal</code> for configuration of ACLs etc.
+        <ol>
+        <li><h5><a id="security_sasl_plain_brokerconfig" href="#security_sasl_plain_brokerconfig">Configuring Kafka Brokers</a></h5>
+            <ol>
+            <li>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:
+                <pre>
+        KafkaServer {
+            org.apache.kafka.common.security.plain.PlainLoginModule required
+            username="admin"
+            password="admin-secret"
+            user_admin="admin-secret"
+            user_alice="alice-secret";
+        };</pre>
+                This configuration defines two users (<i>admin</i> and <i>alice</i>). The properties <tt>username</tt> and <tt>password</tt>
+                in the <tt>KafkaServer</tt> section are used by the broker to initiate connections to other brokers. In this example,
+                <i>admin</i> is the user for inter-broker communication. The set of properties <tt>user_<i>userName</i></tt> 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.</li>
+            <li>Pass the JAAS config file location as JVM parameter to each Kafka broker:
+                <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf</pre></li>
+            <li>Configure SASL port and SASL mechanisms in server.properties as described <a href="#security_sasl_brokerconfig">here</a>.</pre> For example:
+                <pre>    listeners=SASL_SSL://host.name:port
+        security.inter.broker.protocol=SASL_SSL
+        sasl.mechanism.inter.broker.protocol=PLAIN
+        sasl.enabled.mechanisms=PLAIN</pre></li>
+            </ol>
+        </li>
 
-        org.apache.kafka.common.security.plain.PlainLoginModule required
-        username="admin"
-        password="admin-secret"
-        user_admin="admin-secret"
-        user_alice="alice-secret";
-    };</pre></li>
-      <li>Enable the SASL mechanisms in server.properties: <pre>    sasl.enabled.mechanisms=GSSAPI,PLAIN</pre></li>
-      <li>Specify the SASL security protocol and mechanism for inter-broker communication in server.properties if required:
-        <pre>    security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
-    sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)</pre></li>
-      <li>Follow the mechanism-specific steps in <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
-          and <a href="#security_sasl_plain_brokerconfig">PLAIN</a> to configure SASL for the enabled mechanisms.</li>
-    </ol>
-  </li>
-  <li><h4><a id="saslmechanism_rolling_upgrade" href="#saslmechanism_rolling_upgrade">Modifying SASL mechanism in a Running Cluster</a></h4>
-    <p>SASL mechanism can be modified in a running cluster using the following sequence:</p>
-    <ol>
-      <li>Enable new SASL mechanism by adding the mechanism to <tt>sasl.enabled.mechanisms</tt> in server.properties for each broker. Update JAAS config file to include both
-        mechanisms as described <a href="#security_sasl_multimechanism">here</a>. Incrementally bounce the cluster nodes.</li>
-      <li>Restart clients using the new mechanism.</li>
-      <li>To change the mechanism of inter-broker communication (if this is required), set <tt>sasl.mechanism.inter.broker.protocol</tt> in server.properties to the new mechanism and
-        incrementally bounce the cluster again.</li>
-      <li>To remove old mechanism (if this is required), remove the old mechanism from <tt>sasl.enabled.mechanisms</tt> in server.properties and remove the entries for the
-        old mechanism from JAAS config file. Incrementally bounce the cluster again.</li>
+        <li><h5><a id="security_sasl_plain_clientconfig" href="#security_sasl_plain_clientconfig">Configuring Kafka Clients</a></h5>
+            To configure SASL authentication on the clients:
+            <ol>
+            <li>The <tt>KafkaClient</tt> 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:
+                <pre>
+        KafkaClient {
+            org.apache.kafka.common.security.plain.PlainLoginModule required
+            username="alice"
+            password="alice-secret";
+        };</pre>
+                The properties <tt>username</tt> and <tt>password</tt> in the <tt>KafkaClient</tt> section are used by clients to configure
+                the user for client connections. In this example, clients connect to the broker as user <i>alice</i>.
+            </li>
+            <li>Pass the JAAS config file location as JVM parameter to each client JVM:
+                <pre>    -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf</pre></li>
+            <li>Configure the following properties in producer.properties or consumer.properties:
+                <pre>    security.protocol=SASL_SSL
+        sasl.mechanism=PLAIN</pre></li>
+            </ol>
+        </li>
+        <li><h5><a id="security_sasl_plain_production" href="#security_sasl_plain_production">Use of SASL/PLAIN in production</a></h5>
+            <ul>
+            <li>SASL/PLAIN should be used only with SSL as transport layer to ensure that clear passwords are not transmitted on the wire without encryption.</li>
+            <li>The default implementation of SASL/PLAIN in Kafka specifies usernames and passwords in the JAAS configuration file as shown
+                <a href="#security_sasl_plain_brokerconfig">here</a>. To avoid storing passwords on disk, you can plug in your own implementation of
+                <code>javax.security.auth.spi.LoginModule</code> 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 <code>Subject</code>. The default implementation
+                <code>org.apache.kafka.common.security.plain.PlainLoginModule</code> can be used as an example.</li>
+            <li>In production systems, external authentication servers may implement password authentication. Kafka brokers can be integrated with these servers by adding
+                your own implementation of <code>javax.security.sasl.SaslServer</code>. The default implementation included in Kafka in the package
+                <code>org.apache.kafka.common.security.plain</code> can be used as an example to get started.
+                <ul>
+                <li>New providers must be installed and registered in the JVM. Providers can be installed by adding provider classes to
+                the normal <tt>CLASSPATH</tt> or bundled as a jar file and added to <tt><i>JAVA_HOME</i>/lib/ext</tt>.</li>
+                <li>Providers can be registered statically by adding a provider to the security properties file
+                <tt><i>JAVA_HOME</i>/lib/security/java.security</tt>.
+                <pre>    security.provider.n=providerClassName</pre>
+                where <i>providerClassName</i> is the fully qualified name of the new provider and <i>n</i> is the preference order with
+                lower numbers indicating higher preference.</li>
+                <li>Alternatively, you can register providers dynamically at runtime by invoking <code>Security.addProvider</code> at the beginning of the client
+                application or in a static initializer in the login module. For example:
+                <pre>    Security.addProvider(new PlainSaslServerProvider());</pre></li>
+                <li>For more details, see <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html">JCA Reference</a>.</li>
+                </ul>
+            </li>
+            </ul>
+        </li>
+        </ol>
+    </li>
+    <li><h4><a id="security_sasl_multimechanism" href="#security_sasl_multimechanism">Enabling multiple SASL mechanisms in a broker</a></h4>
+        <ol>
+        <li>Specify configuration for the login modules of all enabled mechanisms in the <tt>KafkaServer</tt> section of the JAAS config file. For example:
+            <pre>
+        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";
+        };</pre></li>
+        <li>Enable the SASL mechanisms in server.properties: <pre>    sasl.enabled.mechanisms=GSSAPI,PLAIN</pre></li>
+        <li>Specify the SASL security protocol and mechanism for inter-broker communication in server.properties if required:
+            <pre>    security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
+        sasl.mechanism.inter.broker.protocol=GSSAPI (or PLAIN)</pre></li>
+        <li>Follow the mechanism-specific steps in <a href="#security_sasl_kerberos_brokerconfig">GSSAPI (Kerberos)</a>
+            and <a href="#security_sasl_plain_brokerconfig">PLAIN</a> to configure SASL for the enabled mechanisms.</li>
+        </ol>
+    </li>
+    <li><h4><a id="saslmechanism_rolling_upgrade" href="#saslmechanism_rolling_upgrade">Modifying SASL mechanism in a Running Cluster</a></h4>
+        <p>SASL mechanism can be modified in a running cluster using the following sequence:</p>
+        <ol>
+        <li>Enable new SASL mechanism by adding the mechanism to <tt>sasl.enabled.mechanisms</tt> in server.properties for each broker. Update JAAS config file to include both
+            mechanisms as described <a href="#security_sasl_multimechanism">here</a>. Incrementally bounce the cluster nodes.</li>
+        <li>Restart clients using the new mechanism.</li>
+        <li>To change the mechanism of inter-broker communication (if this is required), set <tt>sasl.mechanism.inter.broker.protocol</tt> in server.properties to the new mechanism and
+            incrementally bounce the cluster again.</li>
+        <li>To remove old mechanism (if this is required), remove the old mechanism from <tt>sasl.enabled.mechanisms</tt> in server.properties and remove the entries for the
+            old mechanism from JAAS config file. Incrementally bounce the cluster again.</li>
+        </ol>
+    </li>
     </ol>
-  </li>
-</ol>
-
-<h3><a id="security_authz" href="#security_authz">7.4 Authorization and ACLs</a></h3>
-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.
-<pre>allow.everyone.if.no.acl.found=true</pre>
-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).
-<pre>super.users=User:Bob;User:Alice</pre>
-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.
-<pre>principal.builder.class=CustomizedPrincipalBuilderClass</pre>
-By default, the SASL user name will be the primary part of the Kerberos principal. One can change that by setting <code>sasl.kerberos.principal.to.local.rules</code> to a customized rule in broker.properties.
-The format of <code>sasl.kerberos.principal.to.local.rules</code> is a list where each rule works in the same way as the auth_to_local in <a href="http://web.mit.edu/Kerberos/krb5-latest/doc/admin/conf_files/krb5_conf.html">Kerberos configuration file (krb5.conf)</a>. 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:
-<pre>sasl.kerberos.principal.to.local.rules=RULE:[1:$1@$0](.*@MYDOMAIN.COM)s/@.*//,DEFAULT</pre>
-
-<h4><a id="security_authz_cli" href="#security_authz_cli">Command Line Interface</a></h4>
-Kafka Authorization management CLI can be found under bin directory with all the other CLIs. The CLI script is called <b>kafka-acls.sh</b>. Following lists all the options that the script supports:
-<p></p>
-<table class="data-table">
-    <tr>
-        <th>Option</th>
-        <th>Description</th>
-        <th>Default</th>
-        <th>Option type</th>
-    </tr>
-    <tr>
-        <td>--add</td>
-        <td>Indicates to the script that user is trying to add an acl.</td>
-        <td></td>
-        <td>Action</td>
-    </tr>
-    <tr>
-        <td>--remove</td>
-        <td>Indicates to the script that user is trying to remove an acl.</td>
-        <td></td>
-        <td>Action</td>
-    </tr>
-    <tr>
-        <td>--list</td>
-        <td>Indicates to the script that user is trying to list acls.</td>
-        <td></td>
-        <td>Action</td>
-    </tr>
-    <tr>
-        <td>--authorizer</td>
-        <td>Fully qualified class name of the authorizer.</td>
-        <td>kafka.security.auth.SimpleAclAuthorizer</td>
-        <td>Configuration</td>
-    </tr>
-    <tr>
-        <td>--authorizer-properties</td>
-        <td>key=val pairs that will be passed to authorizer for initialization. For the default authorizer the example values are: zookeeper.connect=localhost:2181</td>
-        <td></td>
-        <td>Configuration</td>
-    </tr>
-    <tr>
-        <td>--cluster</td>
-        <td>Specifies cluster as resource.</td>
-        <td></td>
-        <td>Resource</td>
-    </tr>
-    <tr>
-        <td>--topic [topic-name]</td>
-        <td>Specifies the topic as resource.</td>
-        <td></td>
-        <td>Resource</td>
-    </tr>
-    <tr>
-        <td>--group [group-name]</td>
-        <td>Specifies the consumer-group as resource.</td>
-        <td></td>
-        <td>Resource</td>
-    </tr>
-    <tr>
-        <td>--allow-principal</td>
-        <td>Principal is in PrincipalType:name format that will be added to ACL with Allow permission. <br>You can specify multiple --allow-principal in a single command.</td>
-        <td></td>
-        <td>Principal</td>
-    </tr>
-    <tr>
-        <td>--deny-principal</td>
-        <td>Principal is in PrincipalType:name format that will be added to ACL with Deny permission. <br>You can specify multiple --deny-principal in a single command.</td>
-        <td></td>
-        <td>Principal</td>
-    </tr>
-    <tr>
-        <td>--allow-host</td>
-        <td>IP address from which principals listed in --allow-principal will have access.</td>
-        <td> if --allow-principal is specified defaults to * which translates to "all hosts"</td>
-        <td>Host</td>
-    </tr>
-    <tr>
-        <td>--deny-host</td>
-        <td>IP address from which principals listed in --deny-principal will be denied access.</td>
-        <td>if --deny-principal is specified defaults to * which translates to "all hosts"</td>
-        <td>Host</td>
-    </tr>
-    <tr>
-        <td>--operation</td>
-        <td>Operation that will be allowed or denied.<br>
-            Valid values are : Read, Write, Create, Delete, Alter, Describe, ClusterAction, All</td>
-        <td>All</td>
-        <td>Operation</td>
-    </tr>
-    <tr>
-        <td>--producer</td>
-        <td> Convenience option to add/remove acls for producer role. This will generate acls that allows WRITE,
-            DESCRIBE on topic and CREATE on cluster.</td>
-        <td></td>
-        <td>Convenience</td>
-    </tr>
-    <tr>
-        <td>--consumer</td>
-        <td> Convenience option to add/remove acls for consumer role. This will generate acls that allows READ,
-            DESCRIBE on topic and READ on consumer-group.</td>
-        <td></td>
-        <td>Convenience</td>
-    </tr>
-    <tr>
-        <td>--force</td>
-        <td> Convenience option to assume yes to all queries and do not prompt.</td>
-        <td></td>
-        <td>Convenience</td>
-    </tr>
-</tbody></table>
-
-<h4><a id="security_authz_examples" href="#security_authz_examples">Examples</a></h4>
-<ul>
-    <li><b>Adding Acls</b><br>
-Suppose you want to add an acl "Principals User:Bob and User:Alice are allowed to perform Operation Read and Write on Topic Test-Topic from IP 198.51.100.0 and IP 198.51.100.1". You can do that by executing the CLI with following options:
-        <pre>bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic</pre>
-        By default, all principals that don't have an explicit acl that allows access for an operation to a resource are denied. In rare cases where an allow acl is defined that allows access to all but some principal we will have to use the --deny-principal and --deny-host option. For example, if we want to allow all users to Read from Test-topic but only deny User:BadBob from IP 198.51.100.3 we can do so using following commands:
-        <pre>bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:* --allow-host * --deny-principal User:BadBob --deny-host 198.51.100.3 --operation Read --topic Test-topic</pre>
-        Note that ``--allow-host`` and ``deny-host`` only support IP addresses (hostnames are not supported).
-        Above examples add acls to a topic by specifying --topic [topic-name] as the resource option. Similarly user can add acls to cluster by specifying --cluster and to a consumer group by specifying --group [group-name].</li>
-
-    <li><b>Removing Acls</b><br>
-            Removing acls is pretty much the same. The only difference is instead of --add option users will have to specify --remove option. To remove the acls added by the first example above we can execute the CLI with following options:
-           <pre> bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --remove --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic </pre></li>
-
-    <li><b>List Acls</b><br>
-            We can list acls for any resource by specifying the --list option with the resource. To list all acls for Test-topic we can execute the CLI with following options:
-            <pre>bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --list --topic Test-topic</pre></li>
-
-    <li><b>Adding or removing a principal as producer or consumer</b><br>
-            The most common use case for acl management are adding/removing a principal as producer or consumer so we added convenience options to handle these cases. In order to add User:Bob as a producer of  Test-topic we can execute the following command:
-           <pre> bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:Bob --producer --topic Test-topic</pre>
-            Similarly to add Alice as a consumer of Test-topic with consumer group Group-1 we just have to pass --consumer option:
-           <pre> bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:Bob --consumer --topic test-topic --group Group-1 </pre>
-            Note that for consumer option we must also specify the consumer group.
-            In order to remove a principal from producer or consumer role we just need to pass --remove option. </li>
-    </ul>
-
-<h3><a id="security_rolling_upgrade" href="#security_rolling_upgrade">7.5 Incorporating Security Features in a Running Cluster</a></h3>
-    You can secure a running cluster via one or more of the supported protocols discussed previously. This is done in phases:
+
+    <h3><a id="security_authz" href="#security_authz">7.4 Authorization and ACLs</a></h3>
+    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.
+    <pre>allow.everyone.if.no.acl.found=true</pre>
+    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).
+    <pre>super.users=User:Bob;User:Alice</pre>
+    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.
+    <pre>principal.builder.class=CustomizedPrincipalBuilderClass</pre>
+    By default, the SASL user name will be the primary part of the Kerberos principal. One can change that by setting <code>sasl.kerberos.principal.to.local.rules</code> to a customized rule in broker.properties.
+    The format of <code>sasl.kerberos.principal.to.local.rules</code> is a list where each rule works in the same way as the auth_to_local in <a href="http://web.mit.edu/Kerberos/krb5-latest/doc/admin/conf_files/krb5_conf.html">Kerberos configuration file (krb5.conf)</a>. 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:
+    <pre>sasl.kerberos.principal.to.local.rules=RULE:[1:$1@$0](.*@MYDOMAIN.COM)s/@.*//,DEFAULT</pre>
+
+    <h4><a id="security_authz_cli" href="#security_authz_cli">Command Line Interface</a></h4>
+    Kafka Authorization management CLI can be found under bin directory with all the other CLIs. The CLI script is called <b>kafka-acls.sh</b>. Following lists all the options that the script supports:
     <p></p>
+    <table class="data-table">
+        <tr>
+            <th>Option</th>
+            <th>Description</th>
+            <th>Default</th>
+            <th>Option type</th>
+        </tr>
+        <tr>
+            <td>--add</td>
+            <td>Indicates to the script that user is trying to add an acl.</td>
+            <td></td>
+            <td>Action</td>
+        </tr>
+        <tr>
+            <td>--remove</td>
+            <td>Indicates to the script that user is trying to remove an acl.</td>
+            <td></td>
+            <td>Action</td>
+        </tr>
+        <tr>
+            <td>--list</td>
+            <td>Indicates to the script that user is trying to list acls.</td>
+            <td></td>
+            <td>Action</td>
+        </tr>
+        <tr>
+            <td>--authorizer</td>
+            <td>Fully qualified class name of the authorizer.</td>
+            <td>kafka.security.auth.SimpleAclAuthorizer</td>
+            <td>Configuration</td>
+        </tr>
+        <tr>
+            <td>--authorizer-properties</td>
+            <td>key=val pairs that will be passed to authorizer for initialization. For the default authorizer the example values are: zookeeper.connect=localhost:2181</td>
+            <td></td>
+            <td>Configuration</td>
+        </tr>
+        <tr>
+            <td>--cluster</td>
+            <td>Specifies cluster as resource.</td>
+            <td></td>
+            <td>Resource</td>
+        </tr>
+        <tr>
+            <td>--topic [topic-name]</td>
+            <td>Specifies the topic as resource.</td>
+            <td></td>
+            <td>Resource</td>
+        </tr>
+        <tr>
+            <td>--group [group-name]</td>
+            <td>Specifies the consumer-group as resource.</td>
+            <td></td>
+            <td>Resource</td>
+        </tr>
+        <tr>
+            <td>--allow-principal</td>
+            <td>Principal is in PrincipalType:name format that will be added to ACL with Allow permission. <br>You can specify multiple --allow-principal in a single command.</td>
+            <td></td>
+            <td>Principal</td>
+        </tr>
+        <tr>
+            <td>--deny-principal</td>
+            <td>Principal is in PrincipalType:name format that will be added to ACL with Deny permission. <br>You can specify multiple --deny-principal in a single command.</td>
+            <td></td>
+            <td>Principal</td>
+        </tr>
+        <tr>
+            <td>--allow-host</td>
+            <td>IP address from which principals listed in --allow-principal will have access.</td>
+            <td> if --allow-principal is specified defaults to * which translates to "all hosts"</td>
+            <td>Host</td>
+        </tr>
+        <tr>
+            <td>--deny-host</td>
+            <td>IP address from which principals listed in --deny-principal will be denied access.</td>
+            <td>if --deny-principal is specified defaults to * which translates to "all hosts"</td>
+            <td>Host</td>
+        </tr>
+        <tr>
+            <td>--operation</td>
+            <td>Operation that will be allowed or denied.<br>
+                Valid values are : Read, Write, Create, Delete, Alter, Describe, ClusterAction, All</td>
+            <td>All</td>
+            <td>Operation</td>
+        </tr>
+        <tr>
+            <td>--producer</td>
+            <td> Convenience option to add/remove acls for producer role. This will generate acls that allows WRITE,
+                DESCRIBE on topic and CREATE on cluster.</td>
+            <td></td>
+            <td>Convenience</td>
+        </tr>
+        <tr>
+            <td>--consumer</td>
+            <td> Convenience option to add/remove acls for consumer role. This will generate acls that allows READ,
+                DESCRIBE on topic and READ on consumer-group.</td>
+            <td></td>
+            <td>Convenience</td>
+        </tr>
+        <tr>
+            <td>--force</td>
+            <td> Convenience option to assume yes to all queries and do not prompt.</td>
+            <td></td>
+            <td>Convenience</td>
+        </tr>
+    </tbody></table>
+
+    <h4><a id="security_authz_

<TRUNCATED>

[8/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
Separate Streams documentation and setup docs with easy to set variables

- Seperate Streams documentation out to a standalone page.
- Setup templates to use handlebars.js
- Create template variables to swap in frequently updated values like version number from a single file templateData.js

Author: Derrick Or <de...@gmail.com>

Reviewers: Guozhang Wang <wa...@gmail.com>

Closes #2245 from derrickdoo/docTemplates


Project: http://git-wip-us.apache.org/repos/asf/kafka/repo
Commit: http://git-wip-us.apache.org/repos/asf/kafka/commit/53428694
Tree: http://git-wip-us.apache.org/repos/asf/kafka/tree/53428694
Diff: http://git-wip-us.apache.org/repos/asf/kafka/diff/53428694

Branch: refs/heads/trunk
Commit: 53428694a624a1956cb8fa3a6a674638f9b09816
Parents: 448f194
Author: Derrick Or <de...@gmail.com>
Authored: Tue Dec 13 17:59:49 2016 -0800
Committer: Guozhang Wang <wa...@gmail.com>
Committed: Tue Dec 13 17:59:49 2016 -0800

----------------------------------------------------------------------
 docs/api.html            |  158 +--
 docs/configuration.html  |  474 ++++----
 docs/connect.html        |  594 ++++-----
 docs/design.html         | 1130 ++++++++---------
 docs/documentation.html  |    2 +
 docs/implementation.html |  778 ++++++------
 docs/introduction.html   |  386 +++---
 docs/js/templateData.js  |   21 +
 docs/ops.html            | 2686 +++++++++++++++++++++--------------------
 docs/security.html       | 1350 ++++++++++-----------
 docs/streams.html        |  737 +++++------
 11 files changed, 4215 insertions(+), 4101 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/api.html
----------------------------------------------------------------------
diff --git a/docs/api.html b/docs/api.html
index 366814a..20c3642 100644
--- a/docs/api.html
+++ b/docs/api.html
@@ -15,80 +15,84 @@
  limitations under the License.
 -->
 
-Kafka includes four core apis:
-<ol>
-  <li>The <a href="#producerapi">Producer</a> API allows applications to send streams of data to topics in the Kafka cluster.
-  <li>The <a href="#consumerapi">Consumer</a> API allows applications to read streams of data from topics in the Kafka cluster.
-  <li>The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
-  <li>The <a href="#connectapi">Connect</a> API allows implementing connectors that continually pull from some source system or application into Kafka or push from Kafka into some sink system or application.
-</ol>
-
-Kafka exposes all its functionality over a language independent protocol which has clients available in many programming languages. However only the Java clients are maintained as part of the main Kafka project, the others are available as independent open source projects. A list of non-Java clients is available <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">here</a>.
-
-<h3><a id="producerapi" href="#producerapi">2.1 Producer API</a></h3>
-
-The Producer API allows applications to send streams of data to topics in the Kafka cluster.
-<p>
-Examples showing how to use the producer are given in the
-<a href="/0100/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html" title="Kafka 0.10.0 Javadoc">javadocs</a>.
-<p>
-To use the producer, you can use the following maven dependency:
-
-<pre>
-	&lt;dependency&gt;
-	    &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
-	    &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
-	    &lt;version&gt;0.10.0.0&lt;/version&gt;
-	&lt;/dependency&gt;
-</pre>
-
-<h3><a id="consumerapi" href="#consumerapi">2.2 Consumer API</a></h3>
-
-The Consumer API allows applications to read streams of data from topics in the Kafka cluster.
-<p>
-Examples showing how to use the consumer are given in the
-<a href="/0100/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html" title="Kafka 0.10.0 Javadoc">javadocs</a>.
-<p>
-To use the consumer, you can use the following maven dependency:
-<pre>
-	&lt;dependency&gt;
-	    &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
-	    &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
-	    &lt;version&gt;0.10.0.0&lt;/version&gt;
-	&lt;/dependency&gt;
-</pre>
-
-<h3><a id="streamsapi" href="#streamsapi">2.3 Streams API</a></h3>
-
-The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
-<p>
-Examples showing how to use this library are given in the
-<a href="/0100/javadoc/index.html?org/apache/kafka/streams/KafkaStreams.html" title="Kafka 0.10.0 Javadoc">javadocs</a>
-<p>
-Additional documentation on using the Streams API is available <a href="/documentation.html#streams">here</a>.
-<p>
-To use Kafka Streams you can use the following maven dependency:
-
-<pre>
-	&lt;dependency&gt;
-	    &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
-	    &lt;artifactId&gt;kafka-streams&lt;/artifactId&gt;
-	    &lt;version&gt;0.10.0.0&lt;/version&gt;
-	&lt;/dependency&gt;
-</pre>
-
-<h3><a id="connectapi" href="#connectapi">2.4 Connect API</a></h3>
-
-The Connect API allows implementing connectors that continually pull from some source data system into Kafka or push from Kafka into some sink data system.
-<p>
-Many users of Connect won't need to use this API directly, though, they can use pre-built connectors without needing to write any code. Additional information on using Connect is available <a href="/documentation.html#connect">here</a>.
-<p>
-Those who want to implement custom connectors can see the <a href="/0100/javadoc/index.html?org/apache/kafka/connect" title="Kafka 0.10.0 Javadoc">javadoc</a>.
-<p>
-
-<h3><a id="legacyapis" href="#streamsapi">2.5 Legacy APIs</a></h3>
-
-<p>
-A more limited legacy producer and consumer api is also included in Kafka. These old Scala APIs are deprecated and only still available for compatibility purposes. Information on them can be found here <a href="/081/documentation.html#producerapi"  title="Kafka 0.8.1 Docs">
-here</a>.
-</p>
+<script id="api-template" type="text/x-handlebars-template">
+	Kafka includes four core apis:
+	<ol>
+	<li>The <a href="#producerapi">Producer</a> API allows applications to send streams of data to topics in the Kafka cluster.
+	<li>The <a href="#consumerapi">Consumer</a> API allows applications to read streams of data from topics in the Kafka cluster.
+	<li>The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
+	<li>The <a href="#connectapi">Connect</a> API allows implementing connectors that continually pull from some source system or application into Kafka or push from Kafka into some sink system or application.
+	</ol>
+
+	Kafka exposes all its functionality over a language independent protocol which has clients available in many programming languages. However only the Java clients are maintained as part of the main Kafka project, the others are available as independent open source projects. A list of non-Java clients is available <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">here</a>.
+
+	<h3><a id="producerapi" href="#producerapi">2.1 Producer API</a></h3>
+
+	The Producer API allows applications to send streams of data to topics in the Kafka cluster.
+	<p>
+	Examples showing how to use the producer are given in the
+	<a href="/{{version}}/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html" title="Kafka 0.10.0 Javadoc">javadocs</a>.
+	<p>
+	To use the producer, you can use the following maven dependency:
+
+	<pre>
+		&lt;dependency&gt;
+			&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
+			&lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
+			&lt;version&gt;0.10.0.0&lt;/version&gt;
+		&lt;/dependency&gt;
+	</pre>
+
+	<h3><a id="consumerapi" href="#consumerapi">2.2 Consumer API</a></h3>
+
+	The Consumer API allows applications to read streams of data from topics in the Kafka cluster.
+	<p>
+	Examples showing how to use the consumer are given in the
+	<a href="/{{version}}/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html" title="Kafka 0.10.0 Javadoc">javadocs</a>.
+	<p>
+	To use the consumer, you can use the following maven dependency:
+	<pre>
+		&lt;dependency&gt;
+			&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
+			&lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
+			&lt;version&gt;0.10.0.0&lt;/version&gt;
+		&lt;/dependency&gt;
+	</pre>
+
+	<h3><a id="streamsapi" href="#streamsapi">2.3 Streams API</a></h3>
+
+	The <a href="#streamsapi">Streams</a> API allows transforming streams of data from input topics to output topics.
+	<p>
+	Examples showing how to use this library are given in the
+	<a href="/{{version}}/javadoc/index.html?org/apache/kafka/streams/KafkaStreams.html" title="Kafka 0.10.0 Javadoc">javadocs</a>
+	<p>
+	Additional documentation on using the Streams API is available <a href="/documentation.html#streams">here</a>.
+	<p>
+	To use Kafka Streams you can use the following maven dependency:
+
+	<pre>
+		&lt;dependency&gt;
+			&lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
+			&lt;artifactId&gt;kafka-streams&lt;/artifactId&gt;
+			&lt;version&gt;0.10.0.0&lt;/version&gt;
+		&lt;/dependency&gt;
+	</pre>
+
+	<h3><a id="connectapi" href="#connectapi">2.4 Connect API</a></h3>
+
+	The Connect API allows implementing connectors that continually pull from some source data system into Kafka or push from Kafka into some sink data system.
+	<p>
+	Many users of Connect won't need to use this API directly, though, they can use pre-built connectors without needing to write any code. Additional information on using Connect is available <a href="/documentation.html#connect">here</a>.
+	<p>
+	Those who want to implement custom connectors can see the <a href="/{{version}}/javadoc/index.html?org/apache/kafka/connect" title="Kafka 0.10.0 Javadoc">javadoc</a>.
+	<p>
+
+	<h3><a id="legacyapis" href="#streamsapi">2.5 Legacy APIs</a></h3>
+
+	<p>
+	A more limited legacy producer and consumer api is also included in Kafka. These old Scala APIs are deprecated and only still available for compatibility purposes. Information on them can be found here <a href="/081/documentation.html#producerapi"  title="Kafka 0.8.1 Docs">
+	here</a>.
+	</p>
+</script>
+
+<div class="p-api"></div>

http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/configuration.html
----------------------------------------------------------------------
diff --git a/docs/configuration.html b/docs/configuration.html
index 53343fa..2cad283 100644
--- a/docs/configuration.html
+++ b/docs/configuration.html
@@ -15,239 +15,243 @@
  limitations under the License.
 -->
 
-Kafka uses key-value pairs in the <a href="http://en.wikipedia.org/wiki/.properties">property file format</a> for configuration. These values can be supplied either from a file or programmatically.
-
-<h3><a id="brokerconfigs" href="#brokerconfigs">3.1 Broker Configs</a></h3>
-
-The essential configurations are the following:
-<ul>
-    <li><code>broker.id</code>
-    <li><code>log.dirs</code>
-    <li><code>zookeeper.connect</code>
-</ul>
-
-Topic-level configurations and defaults are discussed in more detail <a href="#topic-config">below</a>.
-
-<!--#include virtual="generated/kafka_config.html" -->
-
-<p>More details about broker configuration can be found in the scala class <code>kafka.server.KafkaConfig</code>.</p>
-
-<a id="topic-config" href="#topic-config">Topic-level configuration</a>
-
-Configurations pertinent to topics have both a server default as well an optional per-topic override. If no per-topic configuration is given the server default is used. The override can be set at topic creation time by giving one or more <code>--config</code> options. This example creates a topic named <i>my-topic</i> with a custom max message size and flush rate:
-<pre>
-<b> &gt; 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</b>
-</pre>
-Overrides can also be changed or set later using the alter configs command. This example updates the max message size for <i>my-topic</i>:
-<pre>
-<b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic --alter --add-config max.message.bytes=128000</b>
-</pre>
-
-To check overrides set on the topic you can do
-<pre>
-<b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic --describe</b>
-</pre>
-
-To remove an override you can do
-<pre>
-<b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181  --entity-type topics --entity-name my-topic --alter --delete-config max.message.bytes</b>
-</pre>
-
-The following are the topic-level configurations. The server's default configuration for this property is given under the Server Default Property heading. A given server default config value only applies to a topic if it does not have an explicit topic config override.
-
-<!--#include virtual="generated/topic_config.html" -->
-
-<h3><a id="producerconfigs" href="#producerconfigs">3.2 Producer Configs</a></h3>
-
-Below is the configuration of the Java producer:
-<!--#include virtual="generated/producer_config.html" -->
-
-<p>
-    For those interested in the legacy Scala producer configs, information can be found <a href="http://kafka.apache.org/082/documentation.html#producerconfigs">
-    here</a>.
-</p>
-
-<h3><a id="consumerconfigs" href="#consumerconfigs">3.3 Consumer Configs</a></h3>
-
-In 0.9.0.0 we introduced the new Java consumer as a replacement for the older Scala-based simple and high-level consumers.
-The configs for both new and old consumers are described below.
-
-<h4><a id="newconsumerconfigs" href="#newconsumerconfigs">3.3.1 New Consumer Configs</a></h4>
-Below is the configuration for the new consumer:
-<!--#include virtual="generated/consumer_config.html" -->
-
-<h4><a id="oldconsumerconfigs" href="#oldconsumerconfigs">3.3.2 Old Consumer Configs</a></h4>
-
-The essential old consumer configurations are the following:
-<ul>
-        <li><code>group.id</code>
-        <li><code>zookeeper.connect</code>
-</ul>
-
-<table class="data-table">
-<tbody><tr>
-        <th>Property</th>
-        <th>Default</th>
-        <th>Description</th>
-</tr>
-    <tr>
-      <td>group.id</td>
-      <td colspan="1"></td>
-      <td>A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group.</td>
-    </tr>
-    <tr>
-      <td>zookeeper.connect</td>
-      <td colspan="1"></td>
-          <td>Specifies the ZooKeeper connection string in the form <code>hostname:port</code> where host and port are the host and port of a ZooKeeper server. To allow connecting through other ZooKeeper nodes when that ZooKeeper machine is down you can also specify multiple hosts in the form <code>hostname1:port1,hostname2:port2,hostname3:port3</code>.
-        <p>
-    The server may also have a ZooKeeper chroot path as part of its ZooKeeper connection string which puts its data under some path in the global ZooKeeper namespace. If so the consumer should use the same chroot path in its connection string. For example to give a chroot path of <code>/chroot/path</code> you would give the connection string as  <code>hostname1:port1,hostname2:port2,hostname3:port3/chroot/path</code>.</td>
-    </tr>
-    <tr>
-      <td>consumer.id</td>
-      <td colspan="1">null</td>
-      <td>
-        <p>Generated automatically if not set.</p>
-     </td>
-    </tr>
-    <tr>
-      <td>socket.timeout.ms</td>
-      <td colspan="1">30 * 1000</td>
-      <td>The socket timeout for network requests. The actual timeout set will be max.fetch.wait + socket.timeout.ms.</td>
-    </tr>
-    <tr>
-      <td>socket.receive.buffer.bytes</td>
-      <td colspan="1">64 * 1024</td>
-      <td>The socket receive buffer for network requests</td>
-    </tr>
-    <tr>
-      <td>fetch.message.max.bytes</td>
-      <td nowrap>1024 * 1024</td>
-      <td>The number of bytes of messages to attempt to fetch for each topic-partition in each fetch request. These bytes will be read into memory for each partition, so this helps control the memory used by the consumer. 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.</td>
-    </tr>
-     <tr>
-      <td>num.consumer.fetchers</td>
-      <td colspan="1">1</td>
-      <td>The number fetcher threads used to fetch data.</td>
-    </tr>
-    <tr>
-      <td>auto.commit.enable</td>
-      <td colspan="1">true</td>
-      <td>If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin.</td>
-    </tr>
-    <tr>
-      <td>auto.commit.interval.ms</td>
-      <td colspan="1">60 * 1000</td>
-      <td>The frequency in ms that the consumer offsets are committed to zookeeper.</td>
-    </tr>
-    <tr>
-      <td>queued.max.message.chunks</td>
-      <td colspan="1">2</td>
-      <td>Max number of message chunks buffered for consumption. Each chunk can be up to fetch.message.max.bytes.</td>
-    </tr>
-    <tr>
-      <td>rebalance.max.retries</td>
-      <td colspan="1">4</td>
-      <td>When a new consumer joins a consumer group the set of consumers attempt to "rebalance" the load to assign partitions to each consumer. If the set of consumers changes while this assignment is taking place the rebalance will fail and retry. This setting controls the maximum number of attempts before giving up.</td>
-    </tr>
-    <tr>
-      <td>fetch.min.bytes</td>
-      <td colspan="1">1</td>
-      <td>The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request.</td>
-    </tr>
-    <tr>
-      <td>fetch.wait.max.ms</td>
-      <td colspan="1">100</td>
-      <td>The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes</td>
-    </tr>
-    <tr>
-      <td>rebalance.backoff.ms</td>
-      <td>2000</td>
-      <td>Backoff time between retries during rebalance. If not set explicitly, the value in zookeeper.sync.time.ms is used.
+<script id="configuration-template" type="text/x-handlebars-template">
+  Kafka uses key-value pairs in the <a href="http://en.wikipedia.org/wiki/.properties">property file format</a> for configuration. These values can be supplied either from a file or programmatically.
+
+  <h3><a id="brokerconfigs" href="#brokerconfigs">3.1 Broker Configs</a></h3>
+
+  The essential configurations are the following:
+  <ul>
+      <li><code>broker.id</code>
+      <li><code>log.dirs</code>
+      <li><code>zookeeper.connect</code>
+  </ul>
+
+  Topic-level configurations and defaults are discussed in more detail <a href="#topic-config">below</a>.
+
+  <!--#include virtual="generated/kafka_config.html" -->
+
+  <p>More details about broker configuration can be found in the scala class <code>kafka.server.KafkaConfig</code>.</p>
+
+  <a id="topic-config" href="#topic-config">Topic-level configuration</a>
+
+  Configurations pertinent to topics have both a server default as well an optional per-topic override. If no per-topic configuration is given the server default is used. The override can be set at topic creation time by giving one or more <code>--config</code> options. This example creates a topic named <i>my-topic</i> with a custom max message size and flush rate:
+  <pre>
+  <b> &gt; 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</b>
+  </pre>
+  Overrides can also be changed or set later using the alter configs command. This example updates the max message size for <i>my-topic</i>:
+  <pre>
+  <b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic --alter --add-config max.message.bytes=128000</b>
+  </pre>
+
+  To check overrides set on the topic you can do
+  <pre>
+  <b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-topic --describe</b>
+  </pre>
+
+  To remove an override you can do
+  <pre>
+  <b> &gt; bin/kafka-configs.sh --zookeeper localhost:2181  --entity-type topics --entity-name my-topic --alter --delete-config max.message.bytes</b>
+  </pre>
+
+  The following are the topic-level configurations. The server's default configuration for this property is given under the Server Default Property heading. A given server default config value only applies to a topic if it does not have an explicit topic config override.
+
+  <!--#include virtual="generated/topic_config.html" -->
+
+  <h3><a id="producerconfigs" href="#producerconfigs">3.2 Producer Configs</a></h3>
+
+  Below is the configuration of the Java producer:
+  <!--#include virtual="generated/producer_config.html" -->
+
+  <p>
+      For those interested in the legacy Scala producer configs, information can be found <a href="http://kafka.apache.org/082/documentation.html#producerconfigs">
+      here</a>.
+  </p>
+
+  <h3><a id="consumerconfigs" href="#consumerconfigs">3.3 Consumer Configs</a></h3>
+
+  In 0.9.0.0 we introduced the new Java consumer as a replacement for the older Scala-based simple and high-level consumers.
+  The configs for both new and old consumers are described below.
+
+  <h4><a id="newconsumerconfigs" href="#newconsumerconfigs">3.3.1 New Consumer Configs</a></h4>
+  Below is the configuration for the new consumer:
+  <!--#include virtual="generated/consumer_config.html" -->
+
+  <h4><a id="oldconsumerconfigs" href="#oldconsumerconfigs">3.3.2 Old Consumer Configs</a></h4>
+
+  The essential old consumer configurations are the following:
+  <ul>
+          <li><code>group.id</code>
+          <li><code>zookeeper.connect</code>
+  </ul>
+
+  <table class="data-table">
+  <tbody><tr>
+          <th>Property</th>
+          <th>Default</th>
+          <th>Description</th>
+  </tr>
+      <tr>
+        <td>group.id</td>
+        <td colspan="1"></td>
+        <td>A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group.</td>
+      </tr>
+      <tr>
+        <td>zookeeper.connect</td>
+        <td colspan="1"></td>
+            <td>Specifies the ZooKeeper connection string in the form <code>hostname:port</code> where host and port are the host and port of a ZooKeeper server. To allow connecting through other ZooKeeper nodes when that ZooKeeper machine is down you can also specify multiple hosts in the form <code>hostname1:port1,hostname2:port2,hostname3:port3</code>.
+          <p>
+      The server may also have a ZooKeeper chroot path as part of its ZooKeeper connection string which puts its data under some path in the global ZooKeeper namespace. If so the consumer should use the same chroot path in its connection string. For example to give a chroot path of <code>/chroot/path</code> you would give the connection string as  <code>hostname1:port1,hostname2:port2,hostname3:port3/chroot/path</code>.</td>
+      </tr>
+      <tr>
+        <td>consumer.id</td>
+        <td colspan="1">null</td>
+        <td>
+          <p>Generated automatically if not set.</p>
       </td>
-    </tr>
-    <tr>
-      <td>refresh.leader.backoff.ms</td>
-      <td colspan="1">200</td>
-      <td>Backoff time to wait before trying to determine the leader of a partition that has just lost its leader.</td>
-    </tr>
-    <tr>
-      <td>auto.offset.reset</td>
-      <td colspan="1">largest</td>
-      <td>
-        <p>What to do when there is no initial offset in ZooKeeper or if an offset is out of range:<br/>* smallest : automatically reset the offset to the smallest offset<br/>* largest : automatically reset the offset to the largest offset<br/>* anything else: throw exception to the consumer</p>
-     </td>
-    </tr>
-    <tr>
-      <td>consumer.timeout.ms</td>
-      <td colspan="1">-1</td>
-      <td>Throw a timeout exception to the consumer if no message is available for consumption after the specified interval</td>
-    </tr>
-     <tr>
-      <td>exclude.internal.topics</td>
-      <td colspan="1">true</td>
-      <td>Whether messages from internal topics (such as offsets) should be exposed to the consumer.</td>
-    </tr>
-    <tr>
-      <td>client.id</td>
-      <td colspan="1">group id value</td>
-      <td>The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request.</td>
-    </tr>
-    <tr>
-      <td>zookeeper.session.timeout.ms�</td>
-      <td colspan="1">6000</td>
-      <td>ZooKeeper session timeout. If the consumer fails to heartbeat to ZooKeeper for this period of time it is considered dead and a rebalance will occur.</td>
-    </tr>
-    <tr>
-      <td>zookeeper.connection.timeout.ms</td>
-      <td colspan="1">6000</td>
-      <td>The max time that the client waits while establishing a connection to zookeeper.</td>
-    </tr>
-    <tr>
-      <td>zookeeper.sync.time.ms�</td>
-      <td colspan="1">2000</td>
-      <td>How far a ZK follower can be behind a ZK leader</td>
-    </tr>
-    <tr>
-      <td>offsets.storage</td>
-      <td colspan="1">zookeeper</td>
-      <td>Select where offsets should be stored (zookeeper or kafka).</td>
-    </tr>
-    <tr>
-      <td>offsets.channel.backoff.ms</td>
-      <td colspan="1">1000</td>
-      <td>The backoff period when reconnecting the offsets channel or retrying failed offset fetch/commit requests.</td>
-    </tr>
-    <tr>
-      <td>offsets.channel.socket.timeout.ms</td>
-      <td colspan="1">10000</td>
-      <td>Socket timeout when reading responses for offset fetch/commit requests. This timeout is also used for ConsumerMetadata requests that are used to query for the offset manager.</td>
-    </tr>
-    <tr>
-      <td>offsets.commit.max.retries</td>
-      <td colspan="1">5</td>
-      <td>Retry the offset commit up to this many times on failure. This retry count only applies to offset commits during shut-down. It does not apply to commits originating from the auto-commit thread. It also does not apply to attempts to query for the offset coordinator before committing offsets. i.e., if a consumer metadata request fails for any reason, it will be retried and that retry does not count toward this limit.</td>
-    </tr>
-    <tr>
-      <td>dual.commit.enabled</td>
-      <td colspan="1">true</td>
-      <td>If you are using "kafka" as offsets.storage, you can dual commit offsets to ZooKeeper (in addition to Kafka). This is required during migration from zookeeper-based offset storage to kafka-based offset storage. With respect to any given consumer group, it is safe to turn this off after all instances within that group have been migrated to the new version that commits offsets to the broker (instead of directly to ZooKeeper).</td>
-    </tr>
-    <tr>
-      <td>partition.assignment.strategy</td>
-      <td colspan="1">range</td>
-      <td><p>Select between the "range" or "roundrobin" strategy for assigning partitions to consumer streams.<p>The round-robin partition assignor lays out all the available partitions and all the available consumer threads. It then proceeds to do a round-robin assignment from partition to consumer thread. If the subscriptions of all consumer instances are identical, then the partitions will be uniformly distributed. (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.<p> Range partitioning works on a per-topic basis. For each topic, we lay out the available partitions in numeric order and the consumer threads in lexicographic order. We then divide the number of partitions by the total number of consumer streams (threads) 
 to determine the number of partitions to assign to each consumer. If it does not evenly divide, then the first few consumers will have one extra partition.</td>
-    </tr>
-</tbody>
-</table>
-
-
-<p>More details about consumer configuration can be found in the scala class <code>kafka.consumer.ConsumerConfig</code>.</p>
-
-<h3><a id="connectconfigs" href="#connectconfigs">3.4 Kafka Connect Configs</a></h3>
-Below is the configuration of the Kafka Connect framework.
-<!--#include virtual="generated/connect_config.html" -->
-
-<h3><a id="streamsconfigs" href="#streamsconfigs">3.5 Kafka Streams Configs</a></h3>
-Below is the configuration of the Kafka Streams client library.
-<!--#include virtual="generated/streams_config.html" -->
+      </tr>
+      <tr>
+        <td>socket.timeout.ms</td>
+        <td colspan="1">30 * 1000</td>
+        <td>The socket timeout for network requests. The actual timeout set will be max.fetch.wait + socket.timeout.ms.</td>
+      </tr>
+      <tr>
+        <td>socket.receive.buffer.bytes</td>
+        <td colspan="1">64 * 1024</td>
+        <td>The socket receive buffer for network requests</td>
+      </tr>
+      <tr>
+        <td>fetch.message.max.bytes</td>
+        <td nowrap>1024 * 1024</td>
+        <td>The number of bytes of messages to attempt to fetch for each topic-partition in each fetch request. These bytes will be read into memory for each partition, so this helps control the memory used by the consumer. 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.</td>
+      </tr>
+      <tr>
+        <td>num.consumer.fetchers</td>
+        <td colspan="1">1</td>
+        <td>The number fetcher threads used to fetch data.</td>
+      </tr>
+      <tr>
+        <td>auto.commit.enable</td>
+        <td colspan="1">true</td>
+        <td>If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin.</td>
+      </tr>
+      <tr>
+        <td>auto.commit.interval.ms</td>
+        <td colspan="1">60 * 1000</td>
+        <td>The frequency in ms that the consumer offsets are committed to zookeeper.</td>
+      </tr>
+      <tr>
+        <td>queued.max.message.chunks</td>
+        <td colspan="1">2</td>
+        <td>Max number of message chunks buffered for consumption. Each chunk can be up to fetch.message.max.bytes.</td>
+      </tr>
+      <tr>
+        <td>rebalance.max.retries</td>
+        <td colspan="1">4</td>
+        <td>When a new consumer joins a consumer group the set of consumers attempt to "rebalance" the load to assign partitions to each consumer. If the set of consumers changes while this assignment is taking place the rebalance will fail and retry. This setting controls the maximum number of attempts before giving up.</td>
+      </tr>
+      <tr>
+        <td>fetch.min.bytes</td>
+        <td colspan="1">1</td>
+        <td>The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request.</td>
+      </tr>
+      <tr>
+        <td>fetch.wait.max.ms</td>
+        <td colspan="1">100</td>
+        <td>The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes</td>
+      </tr>
+      <tr>
+        <td>rebalance.backoff.ms</td>
+        <td>2000</td>
+        <td>Backoff time between retries during rebalance. If not set explicitly, the value in zookeeper.sync.time.ms is used.
+        </td>
+      </tr>
+      <tr>
+        <td>refresh.leader.backoff.ms</td>
+        <td colspan="1">200</td>
+        <td>Backoff time to wait before trying to determine the leader of a partition that has just lost its leader.</td>
+      </tr>
+      <tr>
+        <td>auto.offset.reset</td>
+        <td colspan="1">largest</td>
+        <td>
+          <p>What to do when there is no initial offset in ZooKeeper or if an offset is out of range:<br/>* smallest : automatically reset the offset to the smallest offset<br/>* largest : automatically reset the offset to the largest offset<br/>* anything else: throw exception to the consumer</p>
+      </td>
+      </tr>
+      <tr>
+        <td>consumer.timeout.ms</td>
+        <td colspan="1">-1</td>
+        <td>Throw a timeout exception to the consumer if no message is available for consumption after the specified interval</td>
+      </tr>
+      <tr>
+        <td>exclude.internal.topics</td>
+        <td colspan="1">true</td>
+        <td>Whether messages from internal topics (such as offsets) should be exposed to the consumer.</td>
+      </tr>
+      <tr>
+        <td>client.id</td>
+        <td colspan="1">group id value</td>
+        <td>The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request.</td>
+      </tr>
+      <tr>
+        <td>zookeeper.session.timeout.ms�</td>
+        <td colspan="1">6000</td>
+        <td>ZooKeeper session timeout. If the consumer fails to heartbeat to ZooKeeper for this period of time it is considered dead and a rebalance will occur.</td>
+      </tr>
+      <tr>
+        <td>zookeeper.connection.timeout.ms</td>
+        <td colspan="1">6000</td>
+        <td>The max time that the client waits while establishing a connection to zookeeper.</td>
+      </tr>
+      <tr>
+        <td>zookeeper.sync.time.ms�</td>
+        <td colspan="1">2000</td>
+        <td>How far a ZK follower can be behind a ZK leader</td>
+      </tr>
+      <tr>
+        <td>offsets.storage</td>
+        <td colspan="1">zookeeper</td>
+        <td>Select where offsets should be stored (zookeeper or kafka).</td>
+      </tr>
+      <tr>
+        <td>offsets.channel.backoff.ms</td>
+        <td colspan="1">1000</td>
+        <td>The backoff period when reconnecting the offsets channel or retrying failed offset fetch/commit requests.</td>
+      </tr>
+      <tr>
+        <td>offsets.channel.socket.timeout.ms</td>
+        <td colspan="1">10000</td>
+        <td>Socket timeout when reading responses for offset fetch/commit requests. This timeout is also used for ConsumerMetadata requests that are used to query for the offset manager.</td>
+      </tr>
+      <tr>
+        <td>offsets.commit.max.retries</td>
+        <td colspan="1">5</td>
+        <td>Retry the offset commit up to this many times on failure. This retry count only applies to offset commits during shut-down. It does not apply to commits originating from the auto-commit thread. It also does not apply to attempts to query for the offset coordinator before committing offsets. i.e., if a consumer metadata request fails for any reason, it will be retried and that retry does not count toward this limit.</td>
+      </tr>
+      <tr>
+        <td>dual.commit.enabled</td>
+        <td colspan="1">true</td>
+        <td>If you are using "kafka" as offsets.storage, you can dual commit offsets to ZooKeeper (in addition to Kafka). This is required during migration from zookeeper-based offset storage to kafka-based offset storage. With respect to any given consumer group, it is safe to turn this off after all instances within that group have been migrated to the new version that commits offsets to the broker (instead of directly to ZooKeeper).</td>
+      </tr>
+      <tr>
+        <td>partition.assignment.strategy</td>
+        <td colspan="1">range</td>
+        <td><p>Select between the "range" or "roundrobin" strategy for assigning partitions to consumer streams.<p>The round-robin partition assignor lays out all the available partitions and all the available consumer threads. It then proceeds to do a round-robin assignment from partition to consumer thread. If the subscriptions of all consumer instances are identical, then the partitions will be uniformly distributed. (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.<p> Range partitioning works on a per-topic basis. For each topic, we lay out the available partitions in numeric order and the consumer threads in lexicographic order. We then divide the number of partitions by the total number of consumer streams (threads
 ) to determine the number of partitions to assign to each consumer. If it does not evenly divide, then the first few consumers will have one extra partition.</td>
+      </tr>
+  </tbody>
+  </table>
+
+
+  <p>More details about consumer configuration can be found in the scala class <code>kafka.consumer.ConsumerConfig</code>.</p>
+
+  <h3><a id="connectconfigs" href="#connectconfigs">3.4 Kafka Connect Configs</a></h3>
+  Below is the configuration of the Kafka Connect framework.
+  <!--#include virtual="generated/connect_config.html" -->
+
+  <h3><a id="streamsconfigs" href="#streamsconfigs">3.5 Kafka Streams Configs</a></h3>
+  Below is the configuration of the Kafka Streams client library.
+  <!--#include virtual="generated/streams_config.html" -->
+</script>
+
+<div class="p-configuration"></div>


[3/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/ops.html
----------------------------------------------------------------------
diff --git a/docs/ops.html b/docs/ops.html
index ef889a3..a034b49 100644
--- a/docs/ops.html
+++ b/docs/ops.html
@@ -15,1345 +15,1349 @@
  limitations under the License.
 -->
 
-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.
-
-<h3><a id="basic_ops" href="#basic_ops">6.1 Basic Kafka Operations</a></h3>
-
-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 <code>bin/</code> directory of the Kafka distribution and each tool will print details on all possible commandline options if it is run with no arguments.
-
-<h4><a id="basic_ops_add_topic" href="#basic_ops_add_topic">Adding and removing topics</a></h4>
-
-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 <a href="#topic-config">topic configurations</a> used for auto-created topics.
-<p>
-Topics are added and modified using the topic tool:
-<pre>
- &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --create --topic my_topic_name
-       --partitions 20 --replication-factor 3 --config x=y
-</pre>
-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.
-<p>
-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 <a href="#intro_consumers">concepts section</a>.
-<p>
-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.
-<p>
-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 <a href="#topic-config">here</a>.
-
-<h4><a id="basic_ops_modify_topic" href="#basic_ops_modify_topic">Modifying topics</a></h4>
-
-You can change the configuration or partitioning of a topic using the same topic tool.
-<p>
-To add partitions you can do
-<pre>
- &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name
-       --partitions 40
-</pre>
-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 <code>hash(key) % number_of_partitions</code> then this partitioning will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way.
-<p>
-To add configs:
-<pre>
- &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --config x=y
-</pre>
-To remove a config:
-<pre>
- &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --delete-config x
-</pre>
-And finally deleting a topic:
-<pre>
- &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --delete --topic my_topic_name
-</pre>
-Topic deletion option is disabled by default. To enable it set the server config
-  <pre>delete.topic.enable=true</pre>
-<p>
-Kafka does not currently support reducing the number of partitions for a topic.
-<p>
-Instructions for changing the replication factor of a topic can be found <a href="#basic_ops_increase_replication_factor">here</a>.
-
-<h4><a id="basic_ops_restarting" href="#basic_ops_restarting">Graceful shutdown</a></h4>
-
-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:
-<ol>
-    <li>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.
-    <li>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.
-</ol>
-
-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:
-<pre>
-    controlled.shutdown.enable=true
-</pre>
-Note that controlled shutdown will only succeed if <i>all</i> the partitions hosted on the broker have replicas (i.e. the replication factor is greater than 1 <i>and</i> 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.
-
-<h4><a id="basic_ops_leader_balancing" href="#basic_ops_leader_balancing">Balancing leadership</a></h4>
-
-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.
-<p>
-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:
-<pre>
- &gt; bin/kafka-preferred-replica-election.sh --zookeeper zk_host:port/chroot
-</pre>
-
-Since running this command can be tedious you can also configure Kafka to do this automatically by setting the following configuration:
-<pre>
-    auto.leader.rebalance.enable=true
-</pre>
-
-<h4><a id="basic_ops_racks" href="#basic_ops_racks">Balancing Replicas Across Racks</a></h4>
-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.
-<p></p>
-You can specify that a broker belongs to a particular rack by adding a property to the broker config:
-<pre>   broker.rack=my-rack-id</pre>
-When a topic is <a href="#basic_ops_add_topic">created</a>, <a href="#basic_ops_modify_topic">modified</a> or replicas are <a href="#basic_ops_cluster_expansion">redistributed</a>, 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).
-<p></p>
-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.
-<p></p>
-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.
-
-<h4><a id="basic_ops_mirror_maker" href="#basic_ops_mirror_maker">Mirroring data between clusters</a></h4>
-
-We refer to the process of replicating data <i>between</i> 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 consumes from a source cluster and produces to a destination cluster.
-
-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.
-<p>
-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).
-<p>
-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.
-<p>
-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.
-<p>
-Here is an example showing how to mirror a single topic (named <i>my-topic</i>) from an input cluster:
-<pre>
- &gt; bin/kafka-mirror-maker.sh
-       --consumer.config consumer.properties
-       --producer.config producer.properties --whitelist my-topic
-</pre>
-Note that we specify the list of topics with the <code>--whitelist</code> option. This option allows any regular expression using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">Java-style regular expressions</a>. So you could mirror two topics named <i>A</i> and <i>B</i> using <code>--whitelist 'A|B'</code>. Or you could mirror <i>all</i> topics using <code>--whitelist '*'</code>. 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.
-<p>
-Sometimes it is easier to say what it is that you <i>don't</i> want. Instead of using <code>--whitelist</code> to say what you want
-to mirror you can use <code>--blacklist</code> to say what to exclude. This also takes a regular expression argument.
-However, <code>--blacklist</code> is not supported when the new consumer has been enabled (i.e. when <code>bootstrap.servers</code>
-has been defined in the consumer configuration).
-<p>
-Combining mirroring with the configuration <code>auto.create.topics.enable=true</code> 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.
-
-<h4><a id="basic_ops_consumer_lag" href="#basic_ops_consumer_lag">Checking consumer position</a></h4>
-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 <i>my-group</i> consuming a topic named <i>my-topic</i> would look like this:
-<pre>
- &gt; 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
-</pre>
-
-
-NOTE: Since 0.9.0.0, the kafka.tools.ConsumerOffsetChecker tool has been deprecated. You should use the kafka.admin.ConsumerGroupCommand (or the bin/kafka-consumer-groups.sh script) to manage consumer groups, including consumers created with the <a href="http://kafka.apache.org/documentation.html#newconsumerapi">new consumer API</a>.
-
-<h4><a id="basic_ops_consumer_group" href="#basic_ops_consumer_group">Managing Consumer Groups</a></h4>
-
-With the ConsumerGroupCommand tool, we can list, describe, or delete consumer groups. Note that deletion is only available when the group metadata is stored in
-ZooKeeper. When using the <a href="http://kafka.apache.org/documentation.html#newconsumerapi">new consumer API</a> (where
-the broker handles coordination of partition handling and rebalance), the group is deleted when the last committed offset for that group expires.
-
-For example, to list all consumer groups across all topics:
-
-<pre>
- &gt; bin/kafka-consumer-groups.sh --bootstrap-server broker1:9092 --list
-
-test-consumer-group
-</pre>
-
-To view offsets as in the previous example with the ConsumerOffsetChecker, we "describe" the consumer group like this:
-
-<pre>
- &gt; bin/kafka-consumer-groups.sh --bootstrap-server broker1:9092 --describe --group test-consumer-group
-
-GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
-test-consumer-group            test-foo                       0          1               3               2               consumer-1_/127.0.0.1
-</pre>
-
-If you are using the old high-level consumer and storing the group metadata in ZooKeeper (i.e. <code>offsets.storage=zookeeper</code>), pass
-<code>--zookeeper</code> instead of <code>bootstrap-server</code>:
-
-<pre>
- &gt; bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --list
-</pre>
-
-<h4><a id="basic_ops_cluster_expansion" href="#basic_ops_cluster_expansion">Expanding your cluster</a></h4>
-
-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.
-<p>
-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.
-<p>
-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.
-<p>
-The partition reassignment tool can run in 3 mutually exclusive modes:
-<ul>
-<li>--generate: In this mode, given a list of topics and a list of brokers, the tool generates a candidate reassignment to move all partitions of the specified topics to the new brokers. This option merely provides a convenient way to generate a partition reassignment plan given a list of topics and target brokers.</li>
-<li>--execute: In this mode, the tool kicks off the reassignment of partitions based on the user provided reassignment plan. (using the --reassignment-json-file option). This can either be a custom reassignment plan hand crafted by the admin or provided by using the --generate option</li>
-<li>--verify: In this mode, the tool verifies the status of the reassignment for all partitions listed during the last --execute. The status can be either of successfully completed, failed or in progress</li>
-</ul>
-<h5><a id="basic_ops_automigrate" href="#basic_ops_automigrate">Automatically migrating data to new machines</a></h5>
-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.
-<p>
-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 <i>only</i> exist on brokers 5,6.
-<p>
-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:
-<pre>
-> cat topics-to-move.json
-{"topics": [{"topic": "foo1"},
-            {"topic": "foo2"}],
- "version":1
-}
-</pre>
-Once the json file is ready, use the partition reassignment tool to generate a candidate assignment:
-<pre>
-> 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]}]
-}
-</pre>
-<p>
-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:
-<pre>
-> 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]}]
-}
-</pre>
-<p>
-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:
-<pre>
-> 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
-</pre>
-
-<h5><a id="basic_ops_partitionassignment" href="#basic_ops_partitionassignment">Custom partition assignment and migration</a></h5>
-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
-<p>
-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:
-<p>
-The first step is to hand craft the custom reassignment plan in a json file:
-<pre>
-> cat custom-reassignment.json
-{"version":1,"partitions":[{"topic":"foo1","partition":0,"replicas":[5,6]},{"topic":"foo2","partition":1,"replicas":[2,3]}]}
-</pre>
-Then, use the json file with the --execute option to start the reassignment process:
-<pre>
-> 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]}]
-}
-</pre>
-<p>
-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:
-<pre>
-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
-</pre>
-
-<h4><a id="basic_ops_decommissioning_brokers" href="#basic_ops_decommissioning_brokers">Decommissioning brokers</a></h4>
-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.
-
-<h4><a id="basic_ops_increase_replication_factor" href="#basic_ops_increase_replication_factor">Increasing replication factor</a></h4>
-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.
-<p>
-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.
-<p>
-The first step is to hand craft the custom reassignment plan in a json file:
-<pre>
-> cat increase-replication-factor.json
-{"version":1,
- "partitions":[{"topic":"foo","partition":0,"replicas":[5,6,7]}]}
-</pre>
-Then, use the json file with the --execute option to start the reassignment process:
-<pre>
-> 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]}]}
-</pre>
-<p>
-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:
-<pre>
-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
-</pre>
-You can also verify the increase in replication factor with the kafka-topics tool:
-<pre>
-> 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
-</pre>
-
-<h4><a id="rep-throttle" href="#rep-throttle">Limiting Bandwidth Usage during Data Migration</a></h4>
-Kafka lets you apply a throttle to replication traffic, setting an upper bound on the bandwidth used to move replicas from machine to machine. This is useful when rebalancing a cluster, bootstrapping a new broker or adding or removing brokers, as it limits the impact these data-intensive operations will have on users.
-<p></p>
-There are two interfaces that can be used to engage a throttle. The simplest, and safest, is to apply a throttle when invoking the kafka-reassign-partitions.sh, but kafka-configs.sh can also be used to view and alter the throttle values directly.
-<p></p>
-So for example, if you were to execute a rebalance, with the below command, it would move partitions at no more than 50MB/s.
-<pre>$ bin/kafka-reassign-partitions.sh --zookeeper myhost:2181--execute --reassignment-json-file bigger-cluster.json \u2014throttle 50000000</pre>
-When you execute this script you will see the throttle engage:
-<pre>
-The throttle limit was set to 50000000 B/s
-Successfully started reassignment of partitions.</pre>
-<p>Should you wish to alter the throttle, during a rebalance, say to increase the throughput so it completes quicker, you can do this by re-running the execute command passing the same reassignment-json-file:</p>
-<pre>$ bin/kafka-reassign-partitions.sh --zookeeper localhost:2181  --execute --reassignment-json-file bigger-cluster.json --throttle 700000000
-There is an existing assignment running.
-The throttle limit was set to 700000000 B/s</pre>
-
-<p>Once the rebalance completes the administrator can check the status of the rebalance using the --verify option.
-    If the rebalance has completed, the throttle will be removed via the --verify command. It is important that
-    administrators remove the throttle in a timely manner once rebalancing completes by running the command with
-    the --verify option. Failure to do so could cause regular replication traffic to be throttled. </p>
-<p>When the --verify option is executed, and the reassignment has completed, the script will confirm that the throttle was removed:</p>
-
-<pre>$ bin/kafka-reassign-partitions.sh --zookeeper localhost:2181  --verify --reassignment-json-file bigger-cluster.json
-Status of partition reassignment:
-Reassignment of partition [my-topic,1] completed successfully
-Reassignment of partition [mytopic,0] completed successfully
-Throttle was removed.</pre>
-
-<p>The administrator can also validate the assigned configs using the kafka-configs.sh. There are two pairs of throttle
-    configuration used to manage the throttling process. The throttle value itself. This is configured, at a broker
-    level, using the dynamic properties: </p>
-
-<pre>leader.replication.throttled.rate
-follower.replication.throttled.rate</pre>
-
-<p>There is also an enumerated set of throttled replicas: </p>
-
-<pre>leader.replication.throttled.replicas
-follower.replication.throttled.replicas</pre>
-
-<p>Which are configured per topic. All four config values are automatically assigned by kafka-reassign-partitions.sh
-    (discussed below). </p>
-<p>To view the throttle limit configuration:</p>
-
-<pre>$ bin/kafka-configs.sh --describe --zookeeper localhost:2181 --entity-type brokers
-Configs for brokers '2' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000
-Configs for brokers '1' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000</pre>
-
-<p>This shows the throttle applied to both leader and follower side of the replication protocol. By default both sides
-    are assigned the same throttled throughput value. </p>
-
-<p>To view the list of throttled replicas:</p>
-
-<pre>$ bin/kafka-configs.sh --describe --zookeeper localhost:2181 --entity-type topics
-Configs for topic 'my-topic' are leader.replication.throttled.replicas=1:102,0:101,
-    follower.replication.throttled.replicas=1:101,0:102</pre>
-
-<p>Here we see the leader throttle is applied to partition 1 on broker 102 and partition 0 on broker 101. Likewise the
-    follower throttle is applied to partition 1 on
-    broker 101 and partition 0 on broker 102. </p>
-
-<p>By default kafka-reassign-partitions.sh will apply the leader throttle to all replicas that exist before the
-    rebalance, any one of which might be leader.
-    It will apply the follower throttle to all move destinations. So if there is a partition with replicas on brokers
-    101,102, being reassigned to 102,103, a leader throttle,
-    for that partition, would be applied to 101,102 and a follower throttle would be applied to 103 only. </p>
-
-
-<p>If required, you can also use the --alter switch on kafka-configs.sh to alter the throttle configurations manually.
-</p>
-
-<h5>Safe usage of throttled replication</h5>
-
-<p>Some care should be taken when using throttled replication. In particular:</p>
-
-<p><i>(1) Throttle Removal:</i></p>
-The throttle should be removed in a timely manner once reassignment completes (by running kafka-reassign-partitions
-\u2014verify).
-
-<p><i>(2) Ensuring Progress:</i></p>
-<p>If the throttle is set too low, in comparison to the incoming write rate, it is possible for replication to not
-    make progress. This occurs when:</p>
-<pre>max(BytesInPerSec) > throttle</pre>
-<p>
-    Where BytesInPerSec is the metric that monitors the write throughput of producers into each broker. </p>
-<p>The administrator can monitor whether replication is making progress, during the rebalance, using the metric:</p>
-
-<pre>kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+)</pre>
-
-<p>The lag should constantly decrease during replication.  If the metric does not decrease the administrator should
-    increase the
-    throttle throughput as described above. </p>
-
-
-<h4><a id="quotas" href="#quotas">Setting quotas</a></h4>
-Quotas overrides and defaults may be configured at (user, client-id), user or client-id levels as described <a href="#design_quotas">here</a>.
-By default, clients receive an unlimited quota.
-
-It is possible to set custom quotas for each (user, client-id), user or client-id group.
-<p>
-Configure custom quota for (user=user1, client-id=clientA):
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
-Updated config for entity: user-principal 'user1', client-id 'clientA'.
-</pre>
-
-Configure custom quota for user=user1:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type users --entity-name user1
-Updated config for entity: user-principal 'user1'.
-</pre>
-
-Configure custom quota for client-id=clientA:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type clients --entity-name clientA
-Updated config for entity: client-id 'clientA'.
-</pre>
-
-It is possible to set default quotas for each (user, client-id), user or client-id group by specifying <i>--entity-default</i> option instead of <i>--entity-name</i>.
-<p>
-Configure default client-id quota for user=userA:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type users --entity-name user1 --entity-type clients --entity-default
-Updated config for entity: user-principal 'user1', default client-id.
-</pre>
-
-Configure default quota for user:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type users --entity-default
-Updated config for entity: default user-principal.
-</pre>
-
-Configure default quota for client-id:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048' --entity-type clients --entity-default
-Updated config for entity: default client-id.
-</pre>
-
-Here's how to describe the quota for a given (user, client-id):
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
-Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048
-</pre>
-Describe quota for a given user:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-type users --entity-name user1
-Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048
-</pre>
-Describe quota for a given client-id:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-type clients --entity-name clientA
-Configs for client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048
-</pre>
-If entity name is not specified, all entities of the specified type are described. For example, describe all users:
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-type users
-Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048
-Configs for default user-principal are producer_byte_rate=1024,consumer_byte_rate=2048
-</pre>
-Similarly for (user, client):
-<pre>
-> bin/kafka-configs.sh  --zookeeper localhost:2181 --describe --entity-type users --entity-type clients
-Configs for user-principal 'user1', default client-id are producer_byte_rate=1024,consumer_byte_rate=2048
-Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048
-</pre>
-<p>
-It is possible to set default quotas that apply to all client-ids by setting these configs on the brokers. These properties are applied only if quota overrides or defaults are not configured in Zookeeper. By default, each client-id receives an unlimited quota. The following sets the default quota per producer and consumer client-id to 10MB/sec.
-<pre>
-  quota.producer.default=10485760
-  quota.consumer.default=10485760
-</pre>
-Note that these properties are being deprecated and may be removed in a future release. Defaults configured using kafka-configs.sh take precedence over these properties.
-
-<h3><a id="datacenters" href="#datacenters">6.2 Datacenters</a></h3>
-
-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 <a href="#basic_ops_mirror_maker">mirror maker tool</a> for how to do this).
-<p>
-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.
-<p>
-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 <i>all</i> datacenters. These aggregate clusters are used for reads by applications that require the full data set.
-<p>
-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.
-<p>
-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 <code>socket.send.buffer.bytes</code> and <code>socket.receive.buffer.bytes</code> configurations. The appropriate way to set this is documented <a href="http://en.wikipedia.org/wiki/Bandwidth-delay_product">here</a>.
-<p>
-It is generally <i>not</i> advisable to run a <i>single</i> 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.
-
-<h3><a id="config" href="#config">6.3 Kafka Configuration</a></h3>
-
-<h4><a id="clientconfig" href="#clientconfig">Important Client Configurations</a></h4>
-The most important producer configurations control
-<ul>
-    <li>compression</li>
-    <li>sync vs async production</li>
-    <li>batch size (for async producers)</li>
-</ul>
-The most important consumer configuration is the fetch size.
-<p>
-All configurations are documented in the <a href="#configuration">configuration</a> section.
-<p>
-<h4><a id="prodconfig" href="#prodconfig">A Production Server Config</a></h4>
-Here is our production server configuration:
-<pre>
-# 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
-</pre>
-
-Our client configuration varies a fair amount between different use cases.
-
-<h3><a id="java" href="#java">6.4 Java Version</a></h3>
-
-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:
-<pre>
--Xmx6g -Xms6g -XX:MetaspaceSize=96m -XX:+UseG1GC
--XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M
--XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80
-</pre>
-
-For reference, here are the stats on one of LinkedIn's busiest clusters (at peak):
-<ul>
-    <li>60 brokers</li>
-    <li>50k partitions (replication factor 2)</li>
-    <li>800k messages/sec in</li>
-    <li>300 MB/sec inbound, 1 GB/sec+ outbound</li>
-</ul>
-
-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.
-
-<h3><a id="hwandos" href="#hwandos">6.5 Hardware and OS</a></h3>
-We are using dual quad-core Intel Xeon machines with 24GB of memory.
-<p>
-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.
-<p>
-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).
-
-<h4><a id="os" href="#os">OS</a></h4>
-Kafka should run well on any unix system and has been tested on Linux and Solaris.
-<p>
-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.
-<p>
-It is unlikely to require much OS-level tuning, but there are two potentially important OS-level configurations:
-<ul>
-    <li>File descriptor limits: Kafka uses file descriptors for log segments and open connections.  If a broker hosts many partitions, consider that the broker needs at least (number_of_partitions)*(partition_size/segment_size) to track all log segments in addition to the number of connections the broker makes.  We recommend at least 100000 allowed file descriptors for the broker processes as a starting point.
-    <li>Max socket buffer size: can be increased to enable high-performance data transfer between data centers as <a href="http://www.psc.edu/index.php/networking/641-tcp-tune">described here</a>.
-</ul>
-<p>
-
-<h4><a id="diskandfs" href="#diskandfs">Disks and Filesystem</a></h4>
-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.
-<p>
-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.
-<p>
-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.
-<p>
-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.
-
-<h4><a id="appvsosflush" href="#appvsosflush">Application vs. OS Flush Management</a></h4>
-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.
-<p>
-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.
-<p>
-Note that durability in Kafka does not require syncing data to disk, as a failed node will always recover from its replicas.
-<p>
-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.
-<p>
-The drawback of using application level flush settings is that it is less efficient in its disk usage pattern (it gives the OS less leeway to re-order writes) and it can introduce latency as fsync in most Linux filesystems blocks writes to the file whereas the background flushing does much more granular page-level locking.
-<p>
-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.
-
-<h4><a id="linuxflush" href="#linuxflush">Understanding Linux OS Flush Behavior</a></h4>
-
-In Linux, data written to the filesystem is maintained in <a href="http://en.wikipedia.org/wiki/Page_cache">pagecache</a> 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").
-<p>
-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 <a href="http://web.archive.org/web/20160518040713/http://www.westnet.com/~gsmith/content/linux-pdflush.htm">here</a>.
-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.
-<p>
-You can see the current state of OS memory usage by doing
-<pre>
-  &gt; cat /proc/meminfo
-</pre>
-The meaning of these values are described in the link above.
-<p>
-Using pagecache has several advantages over an in-process cache for storing data that will be written out to disk:
-<ul>
-  <li>The I/O scheduler will batch together consecutive small writes into bigger physical writes which improves throughput.
-  <li>The I/O scheduler will attempt to re-sequence writes to minimize movement of the disk head which improves throughput.
-  <li>It automatically uses all the free memory on the machine
-</ul>
-
-<h4><a id="filesystems" href="#filesystems">Filesystem Selection</a></h4>
-<p>Kafka uses regular files on disk, and as such it has no hard dependency on a specific filesystem. The two filesystems which have the most usage, however, are EXT4 and XFS. Historically, EXT4 has had more usage, but recent improvements to the XFS filesystem have shown it to have better performance characteristics for Kafka's workload with no compromise in stability.</p>
-<p>Comparison testing was performed on a cluster with significant message loads, using a variety of filesystem creation and mount options. The primary metric in Kafka that was monitored was the "Request Local Time", indicating the amount of time append operations were taking. XFS resulted in much better local times (160ms vs. 250ms+ for the best EXT4 configuration), as well as lower average wait times. The XFS performance also showed less variability in disk performance.</p>
-<h5><a id="generalfs" href="#generalfs">General Filesystem Notes</a></h5>
-For any filesystem used for data directories, on Linux systems, the following options are recommended to be used at mount time:
-<ul>
-  <li>noatime: This option disables updating of a file's atime (last access time) attribute when the file is read. This can eliminate a significant number of filesystem writes, especially in the case of bootstrapping consumers. Kafka does not rely on the atime attributes at all, so it is safe to disable this.</li>
-</ul>
-<h5><a id="xfs" href="#xfs">XFS Notes</a></h5>
-The XFS filesystem has a significant amount of auto-tuning in place, so it does not require any change in the default settings, either at filesystem creation time or at mount. The only tuning parameters worth considering are:
-<ul>
-  <li>largeio: This affects the preferred I/O size reported by the stat call. While this can allow for higher performance on larger disk writes, in practice it had minimal or no effect on performance.</li>
-  <li>nobarrier: For underlying devices that have battery-backed cache, this option can provide a little more performance by disabling periodic write flushes. However, if the underlying device is well-behaved, it will report to the filesystem that it does not require flushes, and this option will have no effect.</li>
-</ul>
-<h5><a id="ext4" href="#ext4">EXT4 Notes</a></h5>
-EXT4 is a serviceable choice of filesystem for the Kafka data directories, however getting the most performance out of it will require adjusting several mount options. In addition, these options are generally unsafe in a failure scenario, and will result in much more data loss and corruption. For a single broker failure, this is not much of a concern as the disk can be wiped and the replicas rebuilt from the cluster. In a multiple-failure scenario, such as a power outage, this can mean underlying filesystem (and therefore data) corruption that is not easily recoverable. The following options can be adjusted:
-<ul>
-  <li>data=writeback: Ext4 defaults to data=ordered which puts a strong order on some writes. Kafka does not require this ordering as it does very paranoid data recovery on all unflushed log. This setting removes the ordering constraint and seems to significantly reduce latency.
-  <li>Disabling journaling: Journaling is a tradeoff: it makes reboots faster after server crashes but it introduces a great deal of additional locking which adds variance to write performance. Those who don't care about reboot time and want to reduce a major source of write latency spikes can turn off journaling entirely.
-  <li>commit=num_secs: This tunes the frequency with which ext4 commits to its metadata journal. Setting this to a lower value reduces the loss of unflushed data during a crash. Setting this to a higher value will improve throughput.
-  <li>nobh: This setting controls additional ordering guarantees when using data=writeback mode. This should be safe with Kafka as we do not depend on write ordering and improves throughput and latency.
-  <li>delalloc: Delayed allocation means that the filesystem avoid allocating any blocks until the physical write occurs. This allows ext4 to allocate a large extent instead of smaller pages and helps ensure the data is written sequentially. This feature is great for throughput. It does seem to involve some locking in the filesystem which adds a bit of latency variance.
-</ul>
-
-<h3><a id="monitoring" href="#monitoring">6.6 Monitoring</a></h3>
-
-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.
-<p>
-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.
-<p>
-We do graphing and alerting on the following metrics:
-<table class="data-table">
-<tbody><tr>
-      <th>Description</th>
-      <th>Mbean name</th>
-      <th>Normal value</th>
-    </tr>
-    <tr>
-      <td>Message in rate</td>
-      <td>kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Byte in rate</td>
-      <td>kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Request rate</td>
-      <td>kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower}</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Byte out rate</td>
-      <td>kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Log flush rate and time</td>
-      <td>kafka.log:type=LogFlushStats,name=LogFlushRateAndTimeMs</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td># of under replicated partitions (|ISR| &lt |all replicas|)</td>
-      <td>kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions</td>
-      <td>0</td>
-    </tr>
-    <tr>
-      <td>Is controller active on broker</td>
-      <td>kafka.controller:type=KafkaController,name=ActiveControllerCount</td>
-      <td>only one broker in the cluster should have 1</td>
-    </tr>
-    <tr>
-      <td>Leader election rate</td>
-      <td>kafka.controller:type=ControllerStats,name=LeaderElectionRateAndTimeMs</td>
-      <td>non-zero when there are broker failures</td>
-    </tr>
-    <tr>
-      <td>Unclean leader election rate</td>
-      <td>kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec</td>
-      <td>0</td>
-    </tr>
-    <tr>
-      <td>Partition counts</td>
-      <td>kafka.server:type=ReplicaManager,name=PartitionCount</td>
-      <td>mostly even across brokers</td>
-    </tr>
-    <tr>
-      <td>Leader replica counts</td>
-      <td>kafka.server:type=ReplicaManager,name=LeaderCount</td>
-      <td>mostly even across brokers</td>
-    </tr>
-    <tr>
-      <td>ISR shrink rate</td>
-      <td>kafka.server:type=ReplicaManager,name=IsrShrinksPerSec</td>
-      <td>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. </td>
-    </tr>
-    <tr>
-      <td>ISR expansion rate</td>
-      <td>kafka.server:type=ReplicaManager,name=IsrExpandsPerSec</td>
-      <td>See above</td>
-    </tr>
-    <tr>
-      <td>Max lag in messages btw follower and leader replicas</td>
-      <td>kafka.server:type=ReplicaFetcherManager,name=MaxLag,clientId=Replica</td>
-      <td>lag should be proportional to the maximum batch size of a produce request.</td>
-    </tr>
-    <tr>
-      <td>Lag in messages per follower replica</td>
-      <td>kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+)</td>
-      <td>lag should be proportional to the maximum batch size of a produce request.</td>
-    </tr>
-    <tr>
-      <td>Requests waiting in the producer purgatory</td>
-      <td>kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Produce</td>
-      <td>non-zero if ack=-1 is used</td>
-    </tr>
-    <tr>
-      <td>Requests waiting in the fetch purgatory</td>
-      <td>kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Fetch</td>
-      <td>size depends on fetch.wait.max.ms in the consumer</td>
-    </tr>
-    <tr>
-      <td>Request total time</td>
-      <td>kafka.network:type=RequestMetrics,name=TotalTimeMs,request={Produce|FetchConsumer|FetchFollower}</td>
-      <td>broken into queue, local, remote and response send time</td>
-    </tr>
-    <tr>
-      <td>Time the request waits in the request queue</td>
-       <td>kafka.network:type=RequestMetrics,name=RequestQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Time the request is processed at the leader</td>
-      <td>kafka.network:type=RequestMetrics,name=LocalTimeMs,request={Produce|FetchConsumer|FetchFollower}</td>
-      <td></td>
-    </tr>
-    <tr>
-      <td>Time the request waits for the follower</td>
-      <td>kafka.network:type=RequestMetrics,name=RemoteTimeMs,request={Produce|FetchConsumer|FetchFollower}</td>
-      <td>non-zero for produce requests when ack=-1</td>
-    </tr>
-    <tr>
-        <td>Time the request waits in the response queue</td>
-        <td>kafka.network:type=RequestMetrics,name=ResponseQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}</td>
+<script id="ops-template" type="text/x-handlebars-template">
+  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.
+
+  <h3><a id="basic_ops" href="#basic_ops">6.1 Basic Kafka Operations</a></h3>
+
+  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 <code>bin/</code> directory of the Kafka distribution and each tool will print details on all possible commandline options if it is run with no arguments.
+
+  <h4><a id="basic_ops_add_topic" href="#basic_ops_add_topic">Adding and removing topics</a></h4>
+
+  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 <a href="#topic-config">topic configurations</a> used for auto-created topics.
+  <p>
+  Topics are added and modified using the topic tool:
+  <pre>
+  &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --create --topic my_topic_name
+        --partitions 20 --replication-factor 3 --config x=y
+  </pre>
+  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.
+  <p>
+  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 <a href="#intro_consumers">concepts section</a>.
+  <p>
+  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.
+  <p>
+  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 <a href="#topic-config">here</a>.
+
+  <h4><a id="basic_ops_modify_topic" href="#basic_ops_modify_topic">Modifying topics</a></h4>
+
+  You can change the configuration or partitioning of a topic using the same topic tool.
+  <p>
+  To add partitions you can do
+  <pre>
+  &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name
+        --partitions 40
+  </pre>
+  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 <code>hash(key) % number_of_partitions</code> then this partitioning will potentially be shuffled by adding partitions but Kafka will not attempt to automatically redistribute data in any way.
+  <p>
+  To add configs:
+  <pre>
+  &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --config x=y
+  </pre>
+  To remove a config:
+  <pre>
+  &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --alter --topic my_topic_name --delete-config x
+  </pre>
+  And finally deleting a topic:
+  <pre>
+  &gt; bin/kafka-topics.sh --zookeeper zk_host:port/chroot --delete --topic my_topic_name
+  </pre>
+  Topic deletion option is disabled by default. To enable it set the server config
+    <pre>delete.topic.enable=true</pre>
+  <p>
+  Kafka does not currently support reducing the number of partitions for a topic.
+  <p>
+  Instructions for changing the replication factor of a topic can be found <a href="#basic_ops_increase_replication_factor">here</a>.
+
+  <h4><a id="basic_ops_restarting" href="#basic_ops_restarting">Graceful shutdown</a></h4>
+
+  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:
+  <ol>
+      <li>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.
+      <li>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.
+  </ol>
+
+  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:
+  <pre>
+      controlled.shutdown.enable=true
+  </pre>
+  Note that controlled shutdown will only succeed if <i>all</i> the partitions hosted on the broker have replicas (i.e. the replication factor is greater than 1 <i>and</i> 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.
+
+  <h4><a id="basic_ops_leader_balancing" href="#basic_ops_leader_balancing">Balancing leadership</a></h4>
+
+  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.
+  <p>
+  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:
+  <pre>
+  &gt; bin/kafka-preferred-replica-election.sh --zookeeper zk_host:port/chroot
+  </pre>
+
+  Since running this command can be tedious you can also configure Kafka to do this automatically by setting the following configuration:
+  <pre>
+      auto.leader.rebalance.enable=true
+  </pre>
+
+  <h4><a id="basic_ops_racks" href="#basic_ops_racks">Balancing Replicas Across Racks</a></h4>
+  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.
+  <p></p>
+  You can specify that a broker belongs to a particular rack by adding a property to the broker config:
+  <pre>   broker.rack=my-rack-id</pre>
+  When a topic is <a href="#basic_ops_add_topic">created</a>, <a href="#basic_ops_modify_topic">modified</a> or replicas are <a href="#basic_ops_cluster_expansion">redistributed</a>, 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).
+  <p></p>
+  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.
+  <p></p>
+  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.
+
+  <h4><a id="basic_ops_mirror_maker" href="#basic_ops_mirror_maker">Mirroring data between clusters</a></h4>
+
+  We refer to the process of replicating data <i>between</i> 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 consumes from a source cluster and produces to a destination cluster.
+
+  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.
+  <p>
+  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).
+  <p>
+  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.
+  <p>
+  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.
+  <p>
+  Here is an example showing how to mirror a single topic (named <i>my-topic</i>) from an input cluster:
+  <pre>
+  &gt; bin/kafka-mirror-maker.sh
+        --consumer.config consumer.properties
+        --producer.config producer.properties --whitelist my-topic
+  </pre>
+  Note that we specify the list of topics with the <code>--whitelist</code> option. This option allows any regular expression using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">Java-style regular expressions</a>. So you could mirror two topics named <i>A</i> and <i>B</i> using <code>--whitelist 'A|B'</code>. Or you could mirror <i>all</i> topics using <code>--whitelist '*'</code>. 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.
+  <p>
+  Sometimes it is easier to say what it is that you <i>don't</i> want. Instead of using <code>--whitelist</code> to say what you want
+  to mirror you can use <code>--blacklist</code> to say what to exclude. This also takes a regular expression argument.
+  However, <code>--blacklist</code> is not supported when the new consumer has been enabled (i.e. when <code>bootstrap.servers</code>
+  has been defined in the consumer configuration).
+  <p>
+  Combining mirroring with the configuration <code>auto.create.topics.enable=true</code> 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.
+
+  <h4><a id="basic_ops_consumer_lag" href="#basic_ops_consumer_lag">Checking consumer position</a></h4>
+  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 <i>my-group</i> consuming a topic named <i>my-topic</i> would look like this:
+  <pre>
+  &gt; 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
+  </pre>
+
+
+  NOTE: Since 0.9.0.0, the kafka.tools.ConsumerOffsetChecker tool has been deprecated. You should use the kafka.admin.ConsumerGroupCommand (or the bin/kafka-consumer-groups.sh script) to manage consumer groups, including consumers created with the <a href="http://kafka.apache.org/documentation.html#newconsumerapi">new consumer API</a>.
+
+  <h4><a id="basic_ops_consumer_group" href="#basic_ops_consumer_group">Managing Consumer Groups</a></h4>
+
+  With the ConsumerGroupCommand tool, we can list, describe, or delete consumer groups. Note that deletion is only available when the group metadata is stored in
+  ZooKeeper. When using the <a href="http://kafka.apache.org/documentation.html#newconsumerapi">new consumer API</a> (where
+  the broker handles coordination of partition handling and rebalance), the group is deleted when the last committed offset for that group expires.
+
+  For example, to list all consumer groups across all topics:
+
+  <pre>
+  &gt; bin/kafka-consumer-groups.sh --bootstrap-server broker1:9092 --list
+
+  test-consumer-group
+  </pre>
+
+  To view offsets as in the previous example with the ConsumerOffsetChecker, we "describe" the consumer group like this:
+
+  <pre>
+  &gt; bin/kafka-consumer-groups.sh --bootstrap-server broker1:9092 --describe --group test-consumer-group
+
+  GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
+  test-consumer-group            test-foo                       0          1               3               2               consumer-1_/127.0.0.1
+  </pre>
+
+  If you are using the old high-level consumer and storing the group metadata in ZooKeeper (i.e. <code>offsets.storage=zookeeper</code>), pass
+  <code>--zookeeper</code> instead of <code>bootstrap-server</code>:
+
+  <pre>
+  &gt; bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --list
+  </pre>
+
+  <h4><a id="basic_ops_cluster_expansion" href="#basic_ops_cluster_expansion">Expanding your cluster</a></h4>
+
+  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.
+  <p>
+  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.
+  <p>
+  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.
+  <p>
+  The partition reassignment tool can run in 3 mutually exclusive modes:
+  <ul>
+  <li>--generate: In this mode, given a list of topics and a list of brokers, the tool generates a candidate reassignment to move all partitions of the specified topics to the new brokers. This option merely provides a convenient way to generate a partition reassignment plan given a list of topics and target brokers.</li>
+  <li>--execute: In this mode, the tool kicks off the reassignment of partitions based on the user provided reassignment plan. (using the --reassignment-json-file option). This can either be a custom reassignment plan hand crafted by the admin or provided by using the --generate option</li>
+  <li>--verify: In this mode, the tool verifies the status of the reassignment for all partitions listed during the last --execute. The status can be either of successfully completed, failed or in progress</li>
+  </ul>
+  <h5><a id="basic_ops_automigrate" href="#basic_ops_automigrate">Automatically migrating data to new machines</a></h5>
+  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.
+  <p>
+  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 <i>only</i> exist on brokers 5,6.
+  <p>
+  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:
+  <pre>
+  > cat topics-to-move.json
+  {"topics": [{"topic": "foo1"},
+              {"topic": "foo2"}],
+  "version":1
+  }
+  </pre>
+  Once the json file is ready, use the partition reassignment tool to generate a candidate assignment:
+  <pre>
+  > 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]}]
+  }
+  </pre>
+  <p>
+  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:
+  <pre>
+  > 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]}]
+  }
+  </pre>
+  <p>
+  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:
+  <pre>
+  > 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
+  </pre>
+
+  <h5><a id="basic_ops_partitionassignment" href="#basic_ops_partitionassignment">Custom partition assignment and migration</a></h5>
+  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
+  <p>
+  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:
+  <p>
+  The first step is to hand craft the custom reassignment plan in a json file:
+  <pre>
+  > cat custom-reassignment.json
+  {"version":1,"partitions":[{"topic":"foo1","partition":0,"replicas":[5,6]},{"topic":"foo2","partition":1,"replicas":[2,3]}]}
+  </pre>
+  Then, use the json file with the --execute option to start the reassignment process:
+  <pre>
+  > 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]}]
+  }
+  </pre>
+  <p>
+  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:
+  <pre>
+  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
+  </pre>
+
+  <h4><a id="basic_ops_decommissioning_brokers" href="#basic_ops_decommissioning_brokers">Decommissioning brokers</a></h4>
+  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.
+
+  <h4><a id="basic_ops_increase_replication_factor" href="#basic_ops_increase_replication_factor">Increasing replication factor</a></h4>
+  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.
+  <p>
+  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.
+  <p>
+  The first step is to hand craft the custom reassignment plan in a json file:
+  <pre>
+  > cat increase-replication-factor.json
+  {"version":1,
+  "partitions":[{"topic":"foo","partition":0,"replicas":[5,6,7]}]}
+  </pre>
+  Then, use the json file with the --execute option to start the reassignment process:
+  <pre>
+  > 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]}]}
+  </pre>
+  <p>
+  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:
+  <pre>
+  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
+  </pre>
+  You can also verify the increase in replication factor with the kafka-topics tool:
+  <pre>
+  > 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
+  </pre>
+
+  <h4><a id="rep-throttle" href="#rep-throttle">Limiting Bandwidth Usage during Data Migration</a></h4>
+  Kafka lets you apply a throttle to replication traffic, setting an upper bound on the bandwidth used to move replicas from machine to machine. This is useful when rebalancing a cluster, bootstrapping a new broker or adding or removing brokers, as it limits the impact these data-intensive operations will have on users.
+  <p></p>
+  There are two interfaces that can be used to engage a throttle. The simplest, and safest, is to apply a throttle when invoking the kafka-reassign-partitions.sh, but kafka-configs.sh can also be used to view and alter the throttle values directly.
+  <p></p>
+  So for example, if you were to execute a rebalance, with the below command, it would move partitions at no more than 50MB/s.
+  <pre>$ bin/kafka-reassign-partitions.sh --zookeeper myhost:2181--execute --reassignment-json-file bigger-cluster.json \u2014throttle 50000000</pre>
+  When you execute this script you will see the throttle engage:
+  <pre>
+  The throttle limit was set to 50000000 B/s
+  Successfully started reassignment of partitions.</pre>
+  <p>Should you wish to alter the throttle, during a rebalance, say to increase the throughput so it completes quicker, you can do this by re-running the execute command passing the same reassignment-json-file:</p>
+  <pre>$ bin/kafka-reassign-partitions.sh --zookeeper localhost:2181  --execute --reassignment-json-file bigger-cluster.json --throttle 700000000
+  There is an existing assignment running.
+  The throttle limit was set to 700000000 B/s</pre>
+
+  <p>Once the rebalance completes the administrator can check the status of the rebalance using the --verify option.
+      If the rebalance has completed, the throttle will be removed via the --verify command. It is important that
+      administrators remove the throttle in a timely manner once rebalancing completes by running the command with
+      the --verify option. Failure to do so could cause regular replication traffic to be throttled. </p>
+  <p>When the --verify option is executed, and the reassignment has completed, the script will confirm that the throttle was removed:</p>
+
+  <pre>$ bin/kafka-reassign-partitions.sh --zookeeper localhost:2181  --verify --reassignment-json-file bigger-cluster.json
+  Status of partition reassignment:
+  Reassignment of partition [my-topic,1] completed successfully
+  Reassignment of partition [mytopic,0] completed successfully
+  Throttle was removed.</pre>
+
+  <p>The administrator can also validate the assigned configs using the kafka-configs.sh. There are two pairs of throttle
+      configuration used to manage the throttling process. The throttle value itself. This is configured, at a broker
+      level, using the dynamic properties: </p>
+
+  <pre>leader.replication.throttled.rate
+  follower.replication.throttled.rate</pre>
+
+  <p>There is also an enumerated set of throttled replicas: </p>
+
+  <pre>leader.replication.throttled.replicas
+  follower.replication.throttled.replicas</pre>
+
+  <p>Which are configured per topic. All four config values are automatically assigned by kafka-reassign-partitions.sh
+      (discussed below). </p>
+  <p>To view the throttle limit configuration:</p>
+
+  <pre>$ bin/kafka-configs.sh --describe --zookeeper localhost:2181 --entity-type brokers
+  Configs for brokers '2' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000
+  Configs for brokers '1' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000</pre>
+
+  <p>This shows the throttle applied to both leader and follower side of the replication protocol. By default both sides
+      are assigned the same throttled throughput value. </p>
+
+  <p>To vi

<TRUNCATED>

[6/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/design.html
----------------------------------------------------------------------
diff --git a/docs/design.html b/docs/design.html
index 57db133..2158432 100644
--- a/docs/design.html
+++ b/docs/design.html
@@ -15,569 +15,573 @@
  limitations under the License.
 -->
 
-<h3><a id="majordesignelements" href="#majordesignelements">4.1 Motivation</a></h3>
-<p>
-We designed Kafka to be able to act as a unified platform for handling all the real-time data feeds <a href="#introduction">a large company might have</a>. To do this we had to think through a fairly broad set of use cases.
-<p>
-It would have to have high-throughput to support high volume event streams such as real-time log aggregation.
-<p>
-It would need to deal gracefully with large data backlogs to be able to support periodic data loads from offline systems.
-<p>
-It also meant the system would have to handle low-latency delivery to handle more traditional messaging use-cases.
-<p>
-We wanted to support partitioned, distributed, real-time processing of these feeds to create new, derived feeds. This motivated our partitioning and consumer model.
-<p>
-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.
-<p>
-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.
-
-<h3><a id="persistence" href="#persistence">4.2 Persistence</a></h3>
-<h4><a id="design_filesystem" href="#design_filesystem">Don't fear the filesystem!</a></h4>
-<p>
-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.
-<p>
-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 <a href="http://en.wikipedia.org/wiki/Non-RAID_drive_architectures">JBOD</a>
-configuration with six 7200rpm SATA RAID-5 array is about 600MB/sec but the performance of random writes is only about 100k/sec&mdash;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 <a href="http://queue.acm.org/detail.cfm?id=1563874">ACM Queue article</a>; they actually find that
-<a href="http://deliveryimages.acm.org/10.1145/1570000/1563874/jacobs3.jpg">sequential disk access can in some cases be faster than random memory access!</a>
-<p>
-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 <i>all</i> 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.
-<p>
-Furthermore, we are building on top of the JVM, and anyone who has spent any time with Java memory usage knows two things:
-<ol>
-    <li>The memory overhead of objects is very high, often doubling the size of the data stored (or worse).</li>
-    <li>Java garbage collection becomes increasingly fiddly and slow as the in-heap data increases.</li>
-</ol>
-<p>
-As a result of these factors using the filesystem and relying on pagecache is superior to maintaining an in-memory cache or other structure&mdash;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.
-<p>
-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.
-<p>
-This style of pagecache-centric design is described in an <a href="http://varnish-cache.org/wiki/ArchitectNotes">article</a> on the design of Varnish here (along with a healthy dose of arrogance).
-
-<h4><a id="design_constanttime" href="#design_constanttime">Constant Time Suffices</a></h4>
-<p>
-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 than twice as slow.
-<p>
-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&mdash;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.
-<p>
-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.
-
-<h3><a id="maximizingefficiency" href="#maximizingefficiency">4.3 Efficiency</a></h3>
-<p>
-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.
-<p>
-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.
-<p>
-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.
-<p>
-The small I/O problem happens both between the client and the server and in the server's own persistent operations.
-<p>
-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.
-<p>
-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.
-<p>
-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).
-<p>
-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 <a href="http://man7.org/linux/man-pages/man2/sendfile.2.html">sendfile system call</a>.
-<p>
-To understand the impact of sendfile, it is important to understand the common data path for transfer of data from file to socket:
-<ol>
-    <li>The operating system reads data from the disk into pagecache in kernel space</li>
-    <li>The application reads the data from kernel space into a user-space buffer</li>
-    <li>The application writes the data back into kernel space into a socket buffer</li>
-    <li>The operating system copies the data from the socket buffer to the NIC buffer where it is sent over the network</li>
-</ol>
-<p>
-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.
-<p>
-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.
-<p>
-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.
-<p>
-For more background on the sendfile and zero-copy support in Java, see this <a href="http://www.ibm.com/developerworks/linux/library/j-zerocopy">article</a>.
-
-<h4><a id="design_compression" href="#design_compression">End-to-end Batch Compression</a></h4>
-<p>
-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.
-<p>
-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.
-<p>
-Kafka supports GZIP, Snappy and LZ4 compression protocols. More details on compression can be found <a href="https://cwiki.apache.org/confluence/display/KAFKA/Compression">here</a>.
-
-<h3><a id="theproducer" href="#theproducer">4.4 The Producer</a></h3>
-
-<h4><a id="design_loadbalancing" href="#design_loadbalancing">Load balancing</a></h4>
-<p>
-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.
-<p>
-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.
-
-<h4><a id="design_asyncsend" href="#design_asyncsend">Asynchronous send</a></h4>
-<p>
-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.
-<p>
-Details on <a href="#producerconfigs">configuration</a> and the <a href="http://kafka.apache.org/082/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html">api</a> for the producer can be found
-elsewhere in the documentation.
-
-<h3><a id="theconsumer" href="#theconsumer">4.5 The Consumer</a></h3>
-
-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.
-
-<h4><a id="design_pull" href="#design_pull">Push vs. pull</a></h4>
-<p>
-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 <a href="http://github.com/facebook/scribe">Scribe</a> and
-<a href="http://flume.apache.org/">Apache Flume</a>, 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.
-<p>
-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.
-<p>
-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).
-<p>
-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.
-
-<h4><a id="design_consumerposition" href="#design_consumerposition">Consumer Position</a></h4>
-Keeping track of <i>what</i> has been consumed is, surprisingly, one of the key performance points of a messaging system.
-<p>
-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.
-<p>
-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 <b>consumed</b> 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 <b>sent</b> not <b>consumed</b> when they are sent; the broker waits for a specific acknowledgement from the consumer to record the
-message as <b>consumed</b>. 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.
-<p>
-Kafka handles this differently. Our topic is divided into a set of totally ordered partitions, each of which is consumed by exactly one consumer within each subscribing consumer group 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.
-<p>
-There is a side benefit of this decision. A consumer can deliberately <i>rewind</i> 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.
-
-<h4><a id="design_offlineload" href="#design_offlineload">Offline Data Load</a></h4>
-
-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.
-<p>
-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&mdash;they simply restart from their original position.
-
-<h3><a id="semantics" href="#semantics">4.6 Message Delivery Semantics</a></h3>
-<p>
-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:
-<ul>
-  <li>
-    <i>At most once</i>&mdash;Messages may be lost but are never redelivered.
-  </li>
-  <li>
-    <i>At least once</i>&mdash;Messages are never lost but may be redelivered.
-  </li>
-  <li>
-    <i>Exactly once</i>&mdash;this is what people actually want, each message is delivered once and only once.
-  </li>
-</ul>
-
-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.
-<p>
-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).
-<p>
-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.
-<p>
-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.
-<p>
-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.
-<p>
-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.
-<ol>
-  <li>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.
-  <li>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).
-  <li>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.
-</ol>
-<p>
-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.
-
-<h3><a id="replication" href="#replication">4.7 Replication</a></h3>
-<p>
-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.
-<p>
-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&mdash;in fact we implement un-replicated topics as replicated topics where the
-replication factor is one.
-<p>
-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&mdash;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).
-<p>
-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.
-<p>
-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
-<ol>
-    <li>A node must be able to maintain its session with ZooKeeper (via ZooKeeper's heartbeat mechanism)
-    <li>If it is a slave it must replicate the writes happening on the leader and not fall "too far" behind
-</ol>
-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.
-<p>
-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).
-<p>
-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.
-<p>
-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.
-<p>
-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.
-
-<h4><a id="design_replicatedlog" href="#design_replicatedlog">Replicated Logs: Quorums, ISRs, and State Machines (Oh my!)</a></h4>
-
-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 <a href="http://en.wikipedia.org/wiki/State_machine_replication">state-machine style</a>.
-<p>
-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.
-<p>
-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.
-<p>
-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.
-<p>
-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 2<i>f</i>+1 replicas. If <i>f</i>+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
-<i>f</i>+1 replicas, then, with no more than <i>f</i> failures, the leader is guaranteed to have all committed messages. This is because among any <i>f</i>+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.
-<p>
-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.
-<p>
-There are a rich variety of algorithms in this family including ZooKeeper's
-<a href="http://web.archive.org/web/20140602093727/http://www.stanford.edu/class/cs347/reading/zab.pdf">Zab</a>,
-<a href="https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf">Raft</a>,
-and <a href="http://pmg.csail.mit.edu/papers/vr-revisited.pdf">Viewstamped Replication</a>.
-The most similar academic publication we are aware of to Kafka's actual implementation is
-<a href="http://research.microsoft.com/apps/pubs/default.aspx?id=66814">PacificA</a> from Microsoft.
-<p>
-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 <a href="http://blog.cloudera.com/blog/2012/10/quorum-based-journaling-in-cdh4-1">majority-vote-based journal</a>, but this more
-expensive approach is not used for the data itself.
-<p>
-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 <i>all</i> 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 <i>f+1</i> replicas, a Kafka topic can tolerate <i>f</i> failures without losing committed messages.
-<p>
-For most use cases we hope to handle, we think this tradeoff is a reasonable one. In practice, to tolerate <i>f</i> 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.
-<p>
-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.
-
-<h4><a id="design_uncleanleader" href="#design_uncleanleader">Unclean leader election: What if they all die?</a></h4>
-
-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.
-<p>
-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:
-<ol>
-    <li>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).
-    <li>Choose the first replica (not necessarily in the ISR) that comes back to life as the leader.
-</ol>
-<p>
-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.
-<p>
-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.
-
-
-<h4><a id="design_ha" href="#design_ha">Availability and Durability Guarantees</a></h4>
-
-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:
-<ol>
-     <li> 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. </li>
-     <li> 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. </li>
-</ol>
-
-
-<h4><a id="design_replicamanagment" href="#design_replicamanagment">Replica Management</a></h4>
-
-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.
-<p>
-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.
-
-<h3><a id="compaction" href="#compaction">4.8 Log Compaction</a></h3>
-
-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.
-<p>
-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).
-<p>
-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):
-<pre>
-    123 => bill@microsoft.com
-            .
-            .
-            .
-    123 => bill@gatesfoundation.org
-            .
-            .
-            .
-    123 => bill@gmail.com
-</pre>
-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. <code>bill@gmail.com</code>). 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.
-<p>
-Let's start by looking at a few use cases where this is useful, then we'll see how it can be used.
-<ol>
-<li><i>Database change subscription</i>. 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.
-<li><i>Event sourcing</i>. 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.
-<li><i>Journaling for high-availability</i>. A process that does local computation can be made fault-tolerant by logging out changes that it makes to its 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,
-<a href="http://samza.apache.org/learn/documentation/0.7.0/container/state-management.html">uses this feature</a> for exactly this purpose.
-</ol>
-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 <a href="http://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">this blog post</a>.
-<p>
-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&mdash;now
-restoring from the beginning of the log no longer recreates the current state as old updates may not be captured at all.
-<p>
-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.
-<p>
-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.
-<p>
-This functionality is inspired by one of LinkedIn's oldest and most successful pieces of infrastructure&mdash;a database changelog caching service called <a href="https://github.com/linkedin/databus">Databus</a>.
-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.
-
-<h4><a id="design_compactionbasics" href="#design_compactionbasics">Log Compaction Basics</a></h4>
-
-Here is a high-level picture that shows the logical structure of a Kafka log with the offset for each message.
-<p>
-<img class="centered" src="images/log_cleaner_anatomy.png">
-<p>
-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&mdash;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.
-<p>
-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.
-<p>
-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:
-<p>
-<img class="centered" src="images/log_compaction.png">
-<p>
-<h4><a id="design_compactionguarantees" href="#design_compactionguarantees">What guarantees does log compaction provide?</a></h4>
-
-Log compaction guarantees the following:
-<ol>
-<li>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. The topic's <code>min.compaction.lag.ms</code> can be used to
-guarantee the minimum length of time must pass after a message is written before it could be compacted. I.e. it provides a lower bound on how long each message will remain in the (uncompacted) head.
-<li>Ordering of messages is always maintained.  Compaction will never re-order messages, just remove some.
-<li>The offset for a message never changes.  It is the permanent identifier for a position in the log.
-<li>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.  Additionally, 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 <code>delete.retention.ms</code> setting (the default is 24 hours).  In other words: since the removal of delete markers happens 
-concurrently with reads, it is possible for a consumer to miss delete markers if it lags by more than <code>delete.retention.ms</code>.
-</ol>
-
-<h4><a id="design_compactiondetails" href="#design_compactiondetails">Log Compaction Details</a></h4>
-
-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:
-<ol>
-<li>It chooses the log that has the highest ratio of log head to log tail
-<li>It creates a succinct summary of the last offset for each key in the head of the log
-<li>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).
-<li>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).
-</ol>
-<p>
-<h4><a id="design_compactionconfig" href="#design_compactionconfig">Configuring The Log Cleaner</a></h4>
-
-The log cleaner is enabled by default. This will start the pool of cleaner threads. 
-To enable log cleaning on a particular topic you can add the log-specific property
-  <pre>  log.cleanup.policy=compact</pre>
-This can be done either at topic creation time or using the alter topic command.
-<p>
-The log cleaner can be configured to retain a minimum amount of the uncompacted "head" of the log. This is enabled by setting the compaction time lag.
-  <pre>  log.cleaner.min.compaction.lag.ms</pre>
-
-This can be used to prevent messages newer than a minimum message age from being subject to compaction. If not set, all log segments are eligible for compaction except for the last segment, i.e. the one currently
-being written to. The active segment will not be compacted even if all of its messages are older than the minimum compaction time lag.
-</p>
-<p>
-Further cleaner configurations are described <a href="/documentation.html#brokerconfigs">here</a>.
-
-<h3><a id="design_quotas" href="#design_quotas">4.9 Quotas</a></h3>
-<p>
-    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 group of clients sharing a quota.
-</p>
-
-<h4><a id="design_quotasnecessary" href="#design_quotasnecessary">Why are quotas necessary?</a></h4>
-<p>
-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.
-</p>
-<h4><a id="design_quotasgroups" href="#design_quotasgroups">Client groups</a></h4>
-    The identity of Kafka clients is the user principal which represents an authenticated user in a secure cluster. In a cluster that supports unauthenticated clients, user principal is a grouping of unauthenticated
-    users
-    chosen by the broker using a configurable <code>PrincipalBuilder</code>. Client-id is a logical grouping of clients with a meaningful name chosen by the client application. The tuple (user, client-id) defines
-    a secure logical group of clients that share both user principal and client-id.
-<p>
-    Quotas can be applied to (user, client-id), user or client-id groups. For a given connection, the most specific quota matching the connection is applied. All connections of a quota group share the quota configured for the group.
-    For example, if (user="test-user", client-id="test-client") has a produce quota of 10MB/sec, this is shared across all producer instances of user "test-user" with the client-id "test-client".
-</p>
-<h4><a id="design_quotasconfig" href="#design_quotasconfig">Quota Configuration</a></h4>
-<p>
-    Quota configuration may be defined for (user, client-id), user and client-id groups. It is possible to override the default quota at any of the quota levels that needs a higher (or even lower) quota.
-    The mechanism is similar to the per-topic log config overrides.
-    User and (user, client-id) quota overrides are written to ZooKeeper under <i><b>/config/users</b></i> and client-id quota overrides are written under <i><b>/config/clients</b></i>.
-    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 <a href="#quotas">here</a> for details.
-    Default quotas for each group may also be updated dynamically using the same mechanism.
-</p>
-<p>
-    The order of precedence for quota configuration is:
+<script id="design-template" type="text/x-handlebars-template">
+    <h3><a id="majordesignelements" href="#majordesignelements">4.1 Motivation</a></h3>
+    <p>
+    We designed Kafka to be able to act as a unified platform for handling all the real-time data feeds <a href="#introduction">a large company might have</a>. To do this we had to think through a fairly broad set of use cases.
+    <p>
+    It would have to have high-throughput to support high volume event streams such as real-time log aggregation.
+    <p>
+    It would need to deal gracefully with large data backlogs to be able to support periodic data loads from offline systems.
+    <p>
+    It also meant the system would have to handle low-latency delivery to handle more traditional messaging use-cases.
+    <p>
+    We wanted to support partitioned, distributed, real-time processing of these feeds to create new, derived feeds. This motivated our partitioning and consumer model.
+    <p>
+    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.
+    <p>
+    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.
+
+    <h3><a id="persistence" href="#persistence">4.2 Persistence</a></h3>
+    <h4><a id="design_filesystem" href="#design_filesystem">Don't fear the filesystem!</a></h4>
+    <p>
+    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.
+    <p>
+    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 <a href="http://en.wikipedia.org/wiki/Non-RAID_drive_architectures">JBOD</a>
+    configuration with six 7200rpm SATA RAID-5 array is about 600MB/sec but the performance of random writes is only about 100k/sec&mdash;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 <a href="http://queue.acm.org/detail.cfm?id=1563874">ACM Queue article</a>; they actually find that
+    <a href="http://deliveryimages.acm.org/10.1145/1570000/1563874/jacobs3.jpg">sequential disk access can in some cases be faster than random memory access!</a>
+    <p>
+    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 <i>all</i> 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.
+    <p>
+    Furthermore, we are building on top of the JVM, and anyone who has spent any time with Java memory usage knows two things:
     <ol>
-        <li>/config/users/&lt;user&gt;/clients/&lt;client-id&gt;</li>
-        <li>/config/users/&lt;user&gt;/clients/&lt;default&gt;</li>
-        <li>/config/users/&lt;user&gt;</li>
-        <li>/config/users/&lt;default&gt;/clients/&lt;client-id&gt;</li>
-        <li>/config/users/&lt;default&gt;/clients/&lt;default&gt;</li>
-        <li>/config/users/&lt;default&gt;</li>
-        <li>/config/clients/&lt;client-id&gt;</li>
-        <li>/config/clients/&lt;default&gt;</li>
+        <li>The memory overhead of objects is very high, often doubling the size of the data stored (or worse).</li>
+        <li>Java garbage collection becomes increasingly fiddly and slow as the in-heap data increases.</li>
     </ol>
+    <p>
+    As a result of these factors using the filesystem and relying on pagecache is superior to maintaining an in-memory cache or other structure&mdash;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.
+    <p>
+    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.
+    <p>
+    This style of pagecache-centric design is described in an <a href="http://varnish-cache.org/wiki/ArchitectNotes">article</a> on the design of Varnish here (along with a healthy dose of arrogance).
+
+    <h4><a id="design_constanttime" href="#design_constanttime">Constant Time Suffices</a></h4>
+    <p>
+    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 than twice as slow.
+    <p>
+    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&mdash;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.
+    <p>
+    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.
+
+    <h3><a id="maximizingefficiency" href="#maximizingefficiency">4.3 Efficiency</a></h3>
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    The small I/O problem happens both between the client and the server and in the server's own persistent operations.
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    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).
+    <p>
+    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 <a href="http://man7.org/linux/man-pages/man2/sendfile.2.html">sendfile system call</a>.
+    <p>
+    To understand the impact of sendfile, it is important to understand the common data path for transfer of data from file to socket:
+    <ol>
+        <li>The operating system reads data from the disk into pagecache in kernel space</li>
+        <li>The application reads the data from kernel space into a user-space buffer</li>
+        <li>The application writes the data back into kernel space into a socket buffer</li>
+        <li>The operating system copies the data from the socket buffer to the NIC buffer where it is sent over the network</li>
+    </ol>
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    For more background on the sendfile and zero-copy support in Java, see this <a href="http://www.ibm.com/developerworks/linux/library/j-zerocopy">article</a>.
+
+    <h4><a id="design_compression" href="#design_compression">End-to-end Batch Compression</a></h4>
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    Kafka supports GZIP, Snappy and LZ4 compression protocols. More details on compression can be found <a href="https://cwiki.apache.org/confluence/display/KAFKA/Compression">here</a>.
+
+    <h3><a id="theproducer" href="#theproducer">4.4 The Producer</a></h3>
+
+    <h4><a id="design_loadbalancing" href="#design_loadbalancing">Load balancing</a></h4>
+    <p>
+    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.
+    <p>
+    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.
+
+    <h4><a id="design_asyncsend" href="#design_asyncsend">Asynchronous send</a></h4>
+    <p>
+    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.
+    <p>
+    Details on <a href="#producerconfigs">configuration</a> and the <a href="http://kafka.apache.org/082/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html">api</a> for the producer can be found
+    elsewhere in the documentation.
+
+    <h3><a id="theconsumer" href="#theconsumer">4.5 The Consumer</a></h3>
+
+    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.
+
+    <h4><a id="design_pull" href="#design_pull">Push vs. pull</a></h4>
+    <p>
+    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 <a href="http://github.com/facebook/scribe">Scribe</a> and
+    <a href="http://flume.apache.org/">Apache Flume</a>, 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.
+    <p>
+    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.
+    <p>
+    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).
+    <p>
+    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.
+
+    <h4><a id="design_consumerposition" href="#design_consumerposition">Consumer Position</a></h4>
+    Keeping track of <i>what</i> has been consumed is, surprisingly, one of the key performance points of a messaging system.
+    <p>
+    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.
+    <p>
+    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 <b>consumed</b> 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 <b>sent</b> not <b>consumed</b> when they are sent; the broker waits for a specific acknowledgement from the consumer to record the
+    message as <b>consumed</b>. 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.
+    <p>
+    Kafka handles this differently. Our topic is divided into a set of totally ordered partitions, each of which is consumed by exactly one consumer within each subscribing consumer group 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.
+    <p>
+    There is a side benefit of this decision. A consumer can deliberately <i>rewind</i> 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.
+
+    <h4><a id="design_offlineload" href="#design_offlineload">Offline Data Load</a></h4>
+
+    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.
+    <p>
+    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&mdash;they simply restart from their original position.
+
+    <h3><a id="semantics" href="#semantics">4.6 Message Delivery Semantics</a></h3>
+    <p>
+    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:
+    <ul>
+    <li>
+        <i>At most once</i>&mdash;Messages may be lost but are never redelivered.
+    </li>
+    <li>
+        <i>At least once</i>&mdash;Messages are never lost but may be redelivered.
+    </li>
+    <li>
+        <i>Exactly once</i>&mdash;this is what people actually want, each message is delivered once and only once.
+    </li>
+    </ul>
+
+    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.
+    <p>
+    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).
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    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.
+    <p>
+    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.
+    <ol>
+    <li>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.
+    <li>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).
+    <li>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 

<TRUNCATED>

[4/8] kafka git commit: Separate Streams documentation and setup docs with easy to set variables

Posted by gu...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/introduction.html
----------------------------------------------------------------------
diff --git a/docs/introduction.html b/docs/introduction.html
index d034683..f1bf488 100644
--- a/docs/introduction.html
+++ b/docs/introduction.html
@@ -14,186 +14,206 @@
  See the License for the specific language governing permissions and
  limitations under the License.
 -->
-<h3> Kafka is <i>a distributed streaming platform</i>. What exactly does that mean?</h3>
-<p>We think of a streaming platform as having three key capabilities:</p>
-<ol>
-	<li>It lets you publish and subscribe to streams of records. In this respect it is similar to a message queue or enterprise messaging system.
-	<li>It lets you store streams of records in a fault-tolerant way.
-	<li>It lets you process streams of records as they occur.
-</ol>
-<p>What is Kafka good for?</p>
-<p>It gets used for two broad classes of application:</p>
-<ol>
-  <li>Building real-time streaming data pipelines that reliably get data between systems or applications
-  <li>Building real-time streaming applications that transform or react to the streams of data
-</ol>
-<p>To understand how Kafka does these things, let's dive in and explore Kafka's capabilities from the bottom up.</p>
-<p>First a few concepts:</p>
-<ul>
-	<li>Kafka is run as a cluster on one or more servers.
-    <li>The Kafka cluster stores streams of <i>records</i> in categories called <i>topics</i>.
-	<li>Each record consists of a key, a value, and a timestamp.
-</ul>
-<p>Kafka has four core APIs:</p>
-<div style="overflow: hidden;">
-    <ul style="float: left; width: 40%;">
-    <li>The <a href="/documentation.html#producerapi">Producer API</a> allows an application to publish a stream records to one or more Kafka topics.
-    <li>The <a href="/documentation.html#consumerapi">Consumer API</a> allows an application to subscribe to one or more topics and process the stream of records produced to them.
-	<li>The <a href="/documentation.html#streams">Streams API</a> allows an application to act as a <i>stream processor</i>, consuming an input stream from one or more topics and producing an output stream to one or more output topics, effectively transforming the input streams to output streams.
-	<li>The <a href="/documentation.html#connect">Connector API</a> allows building and running reusable producers or consumers that connect Kafka topics to existing applications or data systems. For example, a connector to a relational database might capture every change to a table.
-</ul>
-    <img src="images/kafka-apis.png" style="float: right; width: 50%;">
-    </div>
-<p>
-In Kafka the communication between the clients and the servers is done with a simple, high-performance, language agnostic <a href="https://kafka.apache.org/protocol.html">TCP protocol</a>. This protocol is versioned and maintains backwards compatibility with older version. We provide a Java client for Kafka, but clients are available in <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">many languages</a>.</p>
-
-<h4><a id="intro_topics" href="#intro_topics">Topics and Logs</a></h4>
-<p>Let's first dive into the core abstraction Kafka provides for a stream of records&mdash;the topic.</p>
-<p>A topic is a category or feed name to which records are published. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it.</p>
-<p> For each topic, the Kafka cluster maintains a partitioned log that looks like this: </p>
-<img class="centered" src="images/log_anatomy.png">
-
-<p> Each partition is an ordered, immutable sequence of records that is continually appended to&mdash;a structured commit log. The records in the partitions are each assigned a sequential id number called the <i>offset</i> that uniquely identifies each record within the partition.
-</p>
-<p>
-The Kafka cluster retains all published records&mdash;whether or not they have been consumed&mdash;using a configurable retention period. For example, if the retention policy is set to two days, then for the two days after a record is published, it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so storing data for a long time is not a problem.
-</p>
-<img class="centered" src="images/log_consumer.png" style="width:400px">
-<p>
-In fact, the only metadata retained on a per-consumer basis is the offset or position of that consumer in the log. This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads records, but, in fact, since the position is controlled by the consumer it can consume records in any order it likes. For example a consumer can reset to an older offset to reprocess data from the past or skip ahead to the most recent record and start consuming from "now".
-</p>
-<p>
-This combination of features means that Kafka consumers are very cheap&mdash;they can come and go without much impact on the cluster or on other consumers. For example, you can use our command line tools to "tail" the contents of any topic without changing what is consumed by any existing consumers.
-</p>
-<p>
-The partitions in the log serve several purposes. First, they allow the log to scale beyond a size that will fit on a single server. Each individual partition must fit on the servers that host it, but a topic may have many partitions so it can handle an arbitrary amount of data. Second they act as the unit of parallelism&mdash;more on that in a bit.
-</p>
-
-<h4><a id="intro_distribution" href="#intro_distribution">Distribution</a></h4>
-
-<p>
-The partitions of the log are distributed over the servers in the Kafka cluster with each server handling data and requests for a share of the partitions. Each partition is replicated across a configurable number of servers for fault tolerance.
-</p>
-<p>
-Each partition has one server which acts as the "leader" and zero or more servers which act as "followers". The leader handles all read and write requests for the partition while the followers passively replicate the leader. If the leader fails, one of the followers will automatically become the new leader. Each server acts as a leader for some of its partitions and a follower for others so load is well balanced within the cluster.
-</p>
-
-<h4><a id="intro_producers" href="#intro_producers">Producers</a></h4>
-<p>
-Producers publish data to the topics of their choice. The producer is responsible for choosing which record to assign to which partition within the topic. This can be done in a round-robin fashion simply to balance load or it can be done according to some semantic partition function (say based on some key in the record). More on the use of partitioning in a second!
-</p>
-
-<h4><a id="intro_consumers" href="#intro_consumers">Consumers</a></h4>
-
-<p>
-Consumers label themselves with a <i>consumer group</i> name, and each record published to a topic is delivered to one consumer instance within each subscribing consumer group. Consumer instances can be in separate processes or on separate machines.
-</p>
-<p>
-If all the consumer instances have the same consumer group, then the records will effectively be load balanced over the consumer instances.</p>
-<p>
-If all the consumer instances have different consumer groups, then each record will be broadcast to all the consumer processes.
-</p>
-<img class="centered" src="images/consumer-groups.png">
-<p>
-  A two server Kafka cluster hosting four partitions (P0-P3) with two consumer groups. Consumer group A has two consumer instances and group B has four.
-</p>
-
-<p>
-More commonly, however, we have found that topics have a small number of consumer groups, one for each "logical subscriber". Each group is composed of many consumer instances for scalability and fault tolerance. This is nothing more than publish-subscribe semantics where the subscriber is a cluster of consumers instead of a single process.
-</p>
-<p>
-The way consumption is implemented in Kafka is by dividing up the partitions in the log over the consumer instances so that each instance is the exclusive consumer of a "fair share" of partitions at any point in time. This process of maintaining membership in the group is handled by the Kafka protocol dynamically. If new instances join the group they will take over some partitions from other members of the group; if an instance dies, its partitions will be distributed to the remaining instances.
-</p>
-<p>
-Kafka only provides a total order over records <i>within</i> a partition, not between different partitions in a topic. 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 records this can be achieved with a topic that has only one partition, though this will mean only one consumer process per consumer group.
-</p>
-<h4><a id="intro_guarantees" href="#intro_guarantees">Guarantees</a></h4>
-<p>
-At a high-level Kafka gives the following guarantees:
-</p>
-<ul>
-  <li>Messages sent by a producer to a particular topic partition will be appended in the order they are sent. That is, if a record M1 is sent by the same producer as a record M2, and M1 is sent first, then M1 will have a lower offset than M2 and appear earlier in the log.
-  <li>A consumer instance sees records in the order they are stored in the log.
-  <li>For a topic with replication factor N, we will tolerate up to N-1 server failures without losing any records committed to the log.
-</ul>
-<p>
-More details on these guarantees are given in the design section of the documentation.
-</p>
-<h4><a id="kafka_mq" href="#kafka_mq">Kafka as a Messaging System</a></h4>
-<p>
-How does Kafka's notion of streams compare to a traditional enterprise messaging system?
-</p>
-<p>
-Messaging traditionally has two models: <a href="http://en.wikipedia.org/wiki/Message_queue">queuing</a> and <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe</a>. In a queue, a pool of consumers may read from a server and each record goes to one of them; in publish-subscribe the record is broadcast to all consumers. Each of these two models has a strength and a weakness. The strength of queuing is that it allows you to divide up the processing of data over multiple consumer instances, which lets you scale your processing. Unfortunately, queues aren't multi-subscriber&mdash;once one process reads the data it's gone. Publish-subscribe allows you broadcast data to multiple processes, but has no way of scaling processing since every message goes to every subscriber.
-</p>
-<p>
-The consumer group concept in Kafka generalizes these two concepts. As with a queue the consumer group allows you to divide up processing over a collection of processes (the members of the consumer group). As with publish-subscribe, Kafka allows you to broadcast messages to multiple consumer groups.
-</p>
-<p>
-The advantage of Kafka's model is that every topic has both these properties&mdash;it can scale processing and is also multi-subscriber&mdash;there is no need to choose one or the other.
-</p>
-<p>
-Kafka has stronger ordering guarantees than a traditional messaging system, too.
-</p>
-<p>
-A traditional queue retains records in-order on the server, and if multiple consumers consume from the queue then the server hands out records in the order they are stored. However, although the server hands out records in order, the records are delivered asynchronously to consumers, so they may arrive out of order on different consumers. This effectively means the ordering of the records is lost in the presence of parallel consumption. Messaging systems often work around this by having a notion of "exclusive consumer" that allows only one process to consume from a queue, but of course this means that there is no parallelism in processing.
-</p>
-<p>
-Kafka does it better. By having a notion of parallelism&mdash;the partition&mdash;within the topics, Kafka is able to provide both ordering guarantees and load balancing over a pool of consumer processes. This is achieved by assigning the partitions in the topic to the consumers in the consumer group so that each partition is consumed by exactly one consumer in the group. By doing this we ensure that the consumer is the only reader of that partition and consumes the data in order. Since there are many partitions this still balances the load over many consumer instances. Note however that there cannot be more consumer instances in a consumer group than partitions.
-</p>
-
-<h4>Kafka as a Storage System</h4>
-
-<p>
-Any message queue that allows publishing messages decoupled from consuming them is effectively acting as a storage system for the in-flight messages. What is different about Kafka is that it is a very good storage system.
-</p>
-<p>
-Data written to Kafka is written to disk and replicated for fault-tolerance. Kafka allows producers to wait on acknowledgement so that a write isn't considered complete until it is fully replicated and guaranteed to persist even if the server written to fails.
-</p>
-<p>
-The disk structures Kafka uses scale well&mdash;Kafka will perform the same whether you have 50 KB or 50 TB of persistent data on the server.
-</p>
-<p>
-As a result of taking storage seriously and allowing the clients to control their read position, you can think of Kafka as a kind of special purpose distributed filesystem dedicated to high-performance, low-latency commit log storage, replication, and propagation.
-</p>
-<h4>Kafka for Stream Processing</h4>
-<p>
-It isn't enough to just read, write, and store streams of data, the purpose is to enable real-time processing of streams.
-</p>
-<p>
-In Kafka a stream processor is anything that takes continual streams of  data from input topics, performs some processing on this input, and produces continual streams of data to output topics.
-</p>
-<p>
-For example, a retail application might take in input streams of sales and shipments, and output a stream of reorders and price adjustments computed off this data.
-</p>
-<p>
-It is possible to do simple processing directly using the producer and consumer APIs. However for more complex transformations Kafka provides a fully integrated <a href="/documentation.html#streams">Streams API</a>. This allows building applications that do non-trivial processing that compute aggregations off of streams or join streams together.
-</p>
-<p>
-This facility helps solve the hard problems this type of application faces: handling out-of-order data, reprocessing input as code changes, performing stateful computations, etc.
-</p>
-<p>
-The streams API builds on the core primitives Kafka provides: it uses the producer and consumer APIs for input, uses Kafka for stateful storage, and uses the same group mechanism for fault tolerance among the stream processor instances.
-</p>
-<h4>Putting the Pieces Together</h4>
-<p>
-This combination of messaging, storage, and stream processing may seem unusual but it is essential to Kafka's role as a streaming platform.
-</p>
-<p>
-A distributed file system like HDFS allows storing static files for batch processing. Effectively a system like this allows storing and processing <i>historical</i> data from the past.
-</p>
-<p>
-A traditional enterprise messaging system allows processing future messages that will arrive after you subscribe. Applications built in this way process future data as it arrives.
-</p>
-<p>
-Kafka combines both of these capabilities, and the combination is critical both for Kafka usage as a platform for streaming applications as well as for streaming data pipelines.
-</p>
-<p>
-By combining storage and low-latency subscriptions, streaming applications can treat both past and future data the same way. That is a single application can process historical, stored data but rather than ending when it reaches the last record it can keep processing as future data arrives. This is a generalized notion of stream processing that subsumes batch processing as well as message-driven applications.
-</p>
-<p>
-Likewise for streaming data pipelines the combination of subscription to real-time events make it possible to use Kafka for very low-latency pipelines; but the ability to store data reliably make it possible to use it for critical data where the delivery of data must be guaranteed or for integration with offline systems that load data only periodically or may go down for extended periods of time for maintenance. The stream processing facilities make it possible to transform data as it arrives.
-</p>
-<p>
-For more information on the guarantees, apis, and capabilities Kafka provides see the rest of the <a href="/documentation.html">documentation</a>.
-</p>
+
+<script><!--#include virtual="js/templateData.js" --></script>
+
+<script id="introduction-template" type="text/x-handlebars-template">
+  <h3> Kafka is <i>a distributed streaming platform</i>. What exactly does that mean?</h3>
+  <p>We think of a streaming platform as having three key capabilities:</p>
+  <ol>
+    <li>It lets you publish and subscribe to streams of records. In this respect it is similar to a message queue or enterprise messaging system.
+    <li>It lets you store streams of records in a fault-tolerant way.
+    <li>It lets you process streams of records as they occur.
+  </ol>
+  <p>What is Kafka good for?</p>
+  <p>It gets used for two broad classes of application:</p>
+  <ol>
+    <li>Building real-time streaming data pipelines that reliably get data between systems or applications
+    <li>Building real-time streaming applications that transform or react to the streams of data
+  </ol>
+  <p>To understand how Kafka does these things, let's dive in and explore Kafka's capabilities from the bottom up.</p>
+  <p>First a few concepts:</p>
+  <ul>
+    <li>Kafka is run as a cluster on one or more servers.
+      <li>The Kafka cluster stores streams of <i>records</i> in categories called <i>topics</i>.
+    <li>Each record consists of a key, a value, and a timestamp.
+  </ul>
+  <p>Kafka has four core APIs:</p>
+  <div style="overflow: hidden;">
+      <ul style="float: left; width: 40%;">
+      <li>The <a href="/documentation.html#producerapi">Producer API</a> allows an application to publish a stream records to one or more Kafka topics.
+      <li>The <a href="/documentation.html#consumerapi">Consumer API</a> allows an application to subscribe to one or more topics and process the stream of records produced to them.
+    <li>The <a href="/documentation.html#streams">Streams API</a> allows an application to act as a <i>stream processor</i>, consuming an input stream from one or more topics and producing an output stream to one or more output topics, effectively transforming the input streams to output streams.
+    <li>The <a href="/documentation.html#connect">Connector API</a> allows building and running reusable producers or consumers that connect Kafka topics to existing applications or data systems. For example, a connector to a relational database might capture every change to a table.
+  </ul>
+      <img src="/{{version}}/images/kafka-apis.png" style="float: right; width: 50%;">
+      </div>
+  <p>
+  In Kafka the communication between the clients and the servers is done with a simple, high-performance, language agnostic <a href="https://kafka.apache.org/protocol.html">TCP protocol</a>. This protocol is versioned and maintains backwards compatibility with older version. We provide a Java client for Kafka, but clients are available in <a href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">many languages</a>.</p>
+
+  <h4><a id="intro_topics" href="#intro_topics">Topics and Logs</a></h4>
+  <p>Let's first dive into the core abstraction Kafka provides for a stream of records&mdash;the topic.</p>
+  <p>A topic is a category or feed name to which records are published. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it.</p>
+  <p> For each topic, the Kafka cluster maintains a partitioned log that looks like this: </p>
+  <img class="centered" src="/{{version}}/images/log_anatomy.png">
+
+  <p> Each partition is an ordered, immutable sequence of records that is continually appended to&mdash;a structured commit log. The records in the partitions are each assigned a sequential id number called the <i>offset</i> that uniquely identifies each record within the partition.
+  </p>
+  <p>
+  The Kafka cluster retains all published records&mdash;whether or not they have been consumed&mdash;using a configurable retention period. For example, if the retention policy is set to two days, then for the two days after a record is published, it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so storing data for a long time is not a problem.
+  </p>
+  <img class="centered" src="/{{version}}/images/log_consumer.png" style="width:400px">
+  <p>
+  In fact, the only metadata retained on a per-consumer basis is the offset or position of that consumer in the log. This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads records, but, in fact, since the position is controlled by the consumer it can consume records in any order it likes. For example a consumer can reset to an older offset to reprocess data from the past or skip ahead to the most recent record and start consuming from "now".
+  </p>
+  <p>
+  This combination of features means that Kafka consumers are very cheap&mdash;they can come and go without much impact on the cluster or on other consumers. For example, you can use our command line tools to "tail" the contents of any topic without changing what is consumed by any existing consumers.
+  </p>
+  <p>
+  The partitions in the log serve several purposes. First, they allow the log to scale beyond a size that will fit on a single server. Each individual partition must fit on the servers that host it, but a topic may have many partitions so it can handle an arbitrary amount of data. Second they act as the unit of parallelism&mdash;more on that in a bit.
+  </p>
+
+  <h4><a id="intro_distribution" href="#intro_distribution">Distribution</a></h4>
+
+  <p>
+  The partitions of the log are distributed over the servers in the Kafka cluster with each server handling data and requests for a share of the partitions. Each partition is replicated across a configurable number of servers for fault tolerance.
+  </p>
+  <p>
+  Each partition has one server which acts as the "leader" and zero or more servers which act as "followers". The leader handles all read and write requests for the partition while the followers passively replicate the leader. If the leader fails, one of the followers will automatically become the new leader. Each server acts as a leader for some of its partitions and a follower for others so load is well balanced within the cluster.
+  </p>
+
+  <h4><a id="intro_producers" href="#intro_producers">Producers</a></h4>
+  <p>
+  Producers publish data to the topics of their choice. The producer is responsible for choosing which record to assign to which partition within the topic. This can be done in a round-robin fashion simply to balance load or it can be done according to some semantic partition function (say based on some key in the record). More on the use of partitioning in a second!
+  </p>
+
+  <h4><a id="intro_consumers" href="#intro_consumers">Consumers</a></h4>
+
+  <p>
+  Consumers label themselves with a <i>consumer group</i> name, and each record published to a topic is delivered to one consumer instance within each subscribing consumer group. Consumer instances can be in separate processes or on separate machines.
+  </p>
+  <p>
+  If all the consumer instances have the same consumer group, then the records will effectively be load balanced over the consumer instances.</p>
+  <p>
+  If all the consumer instances have different consumer groups, then each record will be broadcast to all the consumer processes.
+  </p>
+  <img class="centered" src="/{{version}}/images/consumer-groups.png">
+  <p>
+    A two server Kafka cluster hosting four partitions (P0-P3) with two consumer groups. Consumer group A has two consumer instances and group B has four.
+  </p>
+
+  <p>
+  More commonly, however, we have found that topics have a small number of consumer groups, one for each "logical subscriber". Each group is composed of many consumer instances for scalability and fault tolerance. This is nothing more than publish-subscribe semantics where the subscriber is a cluster of consumers instead of a single process.
+  </p>
+  <p>
+  The way consumption is implemented in Kafka is by dividing up the partitions in the log over the consumer instances so that each instance is the exclusive consumer of a "fair share" of partitions at any point in time. This process of maintaining membership in the group is handled by the Kafka protocol dynamically. If new instances join the group they will take over some partitions from other members of the group; if an instance dies, its partitions will be distributed to the remaining instances.
+  </p>
+  <p>
+  Kafka only provides a total order over records <i>within</i> a partition, not between different partitions in a topic. 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 records this can be achieved with a topic that has only one partition, though this will mean only one consumer process per consumer group.
+  </p>
+  <h4><a id="intro_guarantees" href="#intro_guarantees">Guarantees</a></h4>
+  <p>
+  At a high-level Kafka gives the following guarantees:
+  </p>
+  <ul>
+    <li>Messages sent by a producer to a particular topic partition will be appended in the order they are sent. That is, if a record M1 is sent by the same producer as a record M2, and M1 is sent first, then M1 will have a lower offset than M2 and appear earlier in the log.
+    <li>A consumer instance sees records in the order they are stored in the log.
+    <li>For a topic with replication factor N, we will tolerate up to N-1 server failures without losing any records committed to the log.
+  </ul>
+  <p>
+  More details on these guarantees are given in the design section of the documentation.
+  </p>
+  <h4><a id="kafka_mq" href="#kafka_mq">Kafka as a Messaging System</a></h4>
+  <p>
+  How does Kafka's notion of streams compare to a traditional enterprise messaging system?
+  </p>
+  <p>
+  Messaging traditionally has two models: <a href="http://en.wikipedia.org/wiki/Message_queue">queuing</a> and <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe</a>. In a queue, a pool of consumers may read from a server and each record goes to one of them; in publish-subscribe the record is broadcast to all consumers. Each of these two models has a strength and a weakness. The strength of queuing is that it allows you to divide up the processing of data over multiple consumer instances, which lets you scale your processing. Unfortunately, queues aren't multi-subscriber&mdash;once one process reads the data it's gone. Publish-subscribe allows you broadcast data to multiple processes, but has no way of scaling processing since every message goes to every subscriber.
+  </p>
+  <p>
+  The consumer group concept in Kafka generalizes these two concepts. As with a queue the consumer group allows you to divide up processing over a collection of processes (the members of the consumer group). As with publish-subscribe, Kafka allows you to broadcast messages to multiple consumer groups.
+  </p>
+  <p>
+  The advantage of Kafka's model is that every topic has both these properties&mdash;it can scale processing and is also multi-subscriber&mdash;there is no need to choose one or the other.
+  </p>
+  <p>
+  Kafka has stronger ordering guarantees than a traditional messaging system, too.
+  </p>
+  <p>
+  A traditional queue retains records in-order on the server, and if multiple consumers consume from the queue then the server hands out records in the order they are stored. However, although the server hands out records in order, the records are delivered asynchronously to consumers, so they may arrive out of order on different consumers. This effectively means the ordering of the records is lost in the presence of parallel consumption. Messaging systems often work around this by having a notion of "exclusive consumer" that allows only one process to consume from a queue, but of course this means that there is no parallelism in processing.
+  </p>
+  <p>
+  Kafka does it better. By having a notion of parallelism&mdash;the partition&mdash;within the topics, Kafka is able to provide both ordering guarantees and load balancing over a pool of consumer processes. This is achieved by assigning the partitions in the topic to the consumers in the consumer group so that each partition is consumed by exactly one consumer in the group. By doing this we ensure that the consumer is the only reader of that partition and consumes the data in order. Since there are many partitions this still balances the load over many consumer instances. Note however that there cannot be more consumer instances in a consumer group than partitions.
+  </p>
+
+  <h4>Kafka as a Storage System</h4>
+
+  <p>
+  Any message queue that allows publishing messages decoupled from consuming them is effectively acting as a storage system for the in-flight messages. What is different about Kafka is that it is a very good storage system.
+  </p>
+  <p>
+  Data written to Kafka is written to disk and replicated for fault-tolerance. Kafka allows producers to wait on acknowledgement so that a write isn't considered complete until it is fully replicated and guaranteed to persist even if the server written to fails.
+  </p>
+  <p>
+  The disk structures Kafka uses scale well&mdash;Kafka will perform the same whether you have 50 KB or 50 TB of persistent data on the server.
+  </p>
+  <p>
+  As a result of taking storage seriously and allowing the clients to control their read position, you can think of Kafka as a kind of special purpose distributed filesystem dedicated to high-performance, low-latency commit log storage, replication, and propagation.
+  </p>
+  <h4>Kafka for Stream Processing</h4>
+  <p>
+  It isn't enough to just read, write, and store streams of data, the purpose is to enable real-time processing of streams.
+  </p>
+  <p>
+  In Kafka a stream processor is anything that takes continual streams of  data from input topics, performs some processing on this input, and produces continual streams of data to output topics.
+  </p>
+  <p>
+  For example, a retail application might take in input streams of sales and shipments, and output a stream of reorders and price adjustments computed off this data.
+  </p>
+  <p>
+  It is possible to do simple processing directly using the producer and consumer APIs. However for more complex transformations Kafka provides a fully integrated <a href="/documentation.html#streams">Streams API</a>. This allows building applications that do non-trivial processing that compute aggregations off of streams or join streams together.
+  </p>
+  <p>
+  This facility helps solve the hard problems this type of application faces: handling out-of-order data, reprocessing input as code changes, performing stateful computations, etc.
+  </p>
+  <p>
+  The streams API builds on the core primitives Kafka provides: it uses the producer and consumer APIs for input, uses Kafka for stateful storage, and uses the same group mechanism for fault tolerance among the stream processor instances.
+  </p>
+  <h4>Putting the Pieces Together</h4>
+  <p>
+  This combination of messaging, storage, and stream processing may seem unusual but it is essential to Kafka's role as a streaming platform.
+  </p>
+  <p>
+  A distributed file system like HDFS allows storing static files for batch processing. Effectively a system like this allows storing and processing <i>historical</i> data from the past.
+  </p>
+  <p>
+  A traditional enterprise messaging system allows processing future messages that will arrive after you subscribe. Applications built in this way process future data as it arrives.
+  </p>
+  <p>
+  Kafka combines both of these capabilities, and the combination is critical both for Kafka usage as a platform for streaming applications as well as for streaming data pipelines.
+  </p>
+  <p>
+  By combining storage and low-latency subscriptions, streaming applications can treat both past and future data the same way. That is a single application can process historical, stored data but rather than ending when it reaches the last record it can keep processing as future data arrives. This is a generalized notion of stream processing that subsumes batch processing as well as message-driven applications.
+  </p>
+  <p>
+  Likewise for streaming data pipelines the combination of subscription to real-time events make it possible to use Kafka for very low-latency pipelines; but the ability to store data reliably make it possible to use it for critical data where the delivery of data must be guaranteed or for integration with offline systems that load data only periodically or may go down for extended periods of time for maintenance. The stream processing facilities make it possible to transform data as it arrives.
+  </p>
+  <p>
+  For more information on the guarantees, apis, and capabilities Kafka provides see the rest of the <a href="/documentation.html">documentation</a>.
+  </p>
+</script>
+
+<!--#include virtual="../includes/_header.htm" -->
+<!--#include virtual="../includes/_top.htm" -->
+<div class="content documentation documentation--current">
+	<!--#include virtual="../includes/_nav.htm" -->
+	<div class="right">
+    <div class="p-introduction"></div>
+  </div>
+</div>
+<!--#include virtual="../includes/_footer.htm" -->
+
+<script>
+// Show selected style on nav item
+$(function() { $('.b-nav__intro').addClass('selected'); });
+</script>

http://git-wip-us.apache.org/repos/asf/kafka/blob/53428694/docs/js/templateData.js
----------------------------------------------------------------------
diff --git a/docs/js/templateData.js b/docs/js/templateData.js
new file mode 100644
index 0000000..40c5da1
--- /dev/null
+++ b/docs/js/templateData.js
@@ -0,0 +1,21 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Define variables for doc templates
+var context={
+    "version": "0101"
+};
\ No newline at end of file