You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by ju...@apache.org on 2016/09/16 05:28:32 UTC

[1/3] kafka git commit: KAFKA-1464; Add a throttling option to the Kafka replication

Repository: kafka
Updated Branches:
  refs/heads/trunk d43666102 -> 143a33bc5


http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ClientQuotaManagerTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ClientQuotaManagerTest.scala b/core/src/test/scala/unit/kafka/server/ClientQuotaManagerTest.scala
index 69e83c0..b14464f 100644
--- a/core/src/test/scala/unit/kafka/server/ClientQuotaManagerTest.scala
+++ b/core/src/test/scala/unit/kafka/server/ClientQuotaManagerTest.scala
@@ -40,7 +40,7 @@ class ClientQuotaManagerTest {
 
   @Test
   def testQuotaParsing() {
-    val clientMetrics = new ClientQuotaManager(config, newMetrics, "producer", time)
+    val clientMetrics = new ClientQuotaManager(config, newMetrics, QuotaType.Produce, time)
 
     // Case 1: Update the quota. Assert that the new quota value is returned
     clientMetrics.updateQuota("p1", new Quota(2000, true))
@@ -77,8 +77,8 @@ class ClientQuotaManagerTest {
   @Test
   def testQuotaViolation() {
     val metrics = newMetrics
-    val clientMetrics = new ClientQuotaManager(config, metrics, "producer", time)
-    val queueSizeMetric = metrics.metrics().get(metrics.metricName("queue-size", "producer", ""))
+    val clientMetrics = new ClientQuotaManager(config, metrics, QuotaType.Produce, time)
+    val queueSizeMetric = metrics.metrics().get(metrics.metricName("queue-size", "Produce", ""))
     try {
       /* We have 10 second windows. Make sure that there is no quota violation
        * if we produce under the quota
@@ -125,16 +125,16 @@ class ClientQuotaManagerTest {
   @Test
   def testExpireThrottleTimeSensor() {
     val metrics = newMetrics
-    val clientMetrics = new ClientQuotaManager(config, metrics, "producer", time)
+    val clientMetrics = new ClientQuotaManager(config, metrics, QuotaType.Produce, time)
     try {
       clientMetrics.recordAndMaybeThrottle("client1", 100, callback)
       // remove the throttle time sensor
-      metrics.removeSensor("producerThrottleTime-client1")
+      metrics.removeSensor("ProduceThrottleTime-client1")
       // should not throw an exception even if the throttle time sensor does not exist.
       val throttleTime = clientMetrics.recordAndMaybeThrottle("client1", 10000, callback)
       assertTrue("Should be throttled", throttleTime > 0)
       // the sensor should get recreated
-      val throttleTimeSensor = metrics.getSensor("producerThrottleTime-client1")
+      val throttleTimeSensor = metrics.getSensor("ProduceThrottleTime-client1")
       assertTrue("Throttle time sensor should exist", throttleTimeSensor != null)
     } finally {
       clientMetrics.shutdown()
@@ -144,21 +144,21 @@ class ClientQuotaManagerTest {
   @Test
   def testExpireQuotaSensors() {
     val metrics = newMetrics
-    val clientMetrics = new ClientQuotaManager(config, metrics, "producer", time)
+    val clientMetrics = new ClientQuotaManager(config, metrics, QuotaType.Produce, time)
     try {
       clientMetrics.recordAndMaybeThrottle("client1", 100, callback)
       // remove all the sensors
-      metrics.removeSensor("producerThrottleTime-client1")
-      metrics.removeSensor("producer-client1")
+      metrics.removeSensor("ProduceThrottleTime-client1")
+      metrics.removeSensor("Produce-client1")
       // should not throw an exception
       val throttleTime = clientMetrics.recordAndMaybeThrottle("client1", 10000, callback)
       assertTrue("Should be throttled", throttleTime > 0)
 
       // all the sensors should get recreated
-      val throttleTimeSensor = metrics.getSensor("producerThrottleTime-client1")
+      val throttleTimeSensor = metrics.getSensor("ProduceThrottleTime-client1")
       assertTrue("Throttle time sensor should exist", throttleTimeSensor != null)
 
-      val byteRateSensor = metrics.getSensor("producer-client1")
+      val byteRateSensor = metrics.getSensor("Produce-client1")
       assertTrue("Byte rate sensor should exist", byteRateSensor != null)
     } finally {
       clientMetrics.shutdown()

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/DynamicConfigChangeTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/DynamicConfigChangeTest.scala b/core/src/test/scala/unit/kafka/server/DynamicConfigChangeTest.scala
index a9df929..bf11332 100644
--- a/core/src/test/scala/unit/kafka/server/DynamicConfigChangeTest.scala
+++ b/core/src/test/scala/unit/kafka/server/DynamicConfigChangeTest.scala
@@ -1,32 +1,32 @@
 /**
- * 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.
- */
+  * 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.
+  */
 package kafka.server
 
 import java.util.Properties
 
-import org.apache.kafka.common.protocol.ApiKeys
+import kafka.log.LogConfig._
+import kafka.server.Constants._
 import org.junit.Assert._
 import org.apache.kafka.common.metrics.Quota
-import org.easymock.{Capture, EasyMock}
+import org.easymock.EasyMock
 import org.junit.Test
 import kafka.integration.KafkaServerTestHarness
 import kafka.utils._
 import kafka.common._
-import kafka.log.LogConfig
 import kafka.admin.{AdminOperationException, AdminUtils}
 
 import scala.collection.Map
@@ -37,19 +37,19 @@ class DynamicConfigChangeTest extends KafkaServerTestHarness {
   @Test
   def testConfigChange() {
     assertTrue("Should contain a ConfigHandler for topics",
-               this.servers.head.dynamicConfigHandlers.contains(ConfigType.Topic))
+      this.servers.head.dynamicConfigHandlers.contains(ConfigType.Topic))
     val oldVal: java.lang.Long = 100000L
     val newVal: java.lang.Long = 200000L
     val tp = TopicAndPartition("test", 0)
     val logProps = new Properties()
-    logProps.put(LogConfig.FlushMessagesProp, oldVal.toString)
+    logProps.put(FlushMessagesProp, oldVal.toString)
     AdminUtils.createTopic(zkUtils, tp.topic, 1, 1, logProps)
     TestUtils.retry(10000) {
       val logOpt = this.servers.head.logManager.getLog(tp)
       assertTrue(logOpt.isDefined)
       assertEquals(oldVal, logOpt.get.config.flushInterval)
     }
-    logProps.put(LogConfig.FlushMessagesProp, newVal.toString)
+    logProps.put(FlushMessagesProp, newVal.toString)
     AdminUtils.changeTopicConfig(zkUtils, tp.topic, logProps)
     TestUtils.retry(10000) {
       assertEquals(newVal, this.servers.head.logManager.getLog(tp).get.config.flushInterval)
@@ -59,21 +59,21 @@ class DynamicConfigChangeTest extends KafkaServerTestHarness {
   @Test
   def testClientQuotaConfigChange() {
     assertTrue("Should contain a ConfigHandler for topics",
-               this.servers.head.dynamicConfigHandlers.contains(ConfigType.Client))
+      this.servers.head.dynamicConfigHandlers.contains(ConfigType.Client))
     val clientId = "testClient"
     val props = new Properties()
     props.put(ClientConfigOverride.ProducerOverride, "1000")
     props.put(ClientConfigOverride.ConsumerOverride, "2000")
     AdminUtils.changeClientIdConfig(zkUtils, clientId, props)
-    val quotaManagers: Map[Short, ClientQuotaManager] = servers.head.apis.quotaManagers
+    val quotaManagers = servers.head.apis.quotas
 
     TestUtils.retry(10000) {
-      val overrideProducerQuota = quotaManagers.get(ApiKeys.PRODUCE.id).get.quota(clientId)
-      val overrideConsumerQuota = quotaManagers.get(ApiKeys.FETCH.id).get.quota(clientId)
+      val overrideProducerQuota = quotaManagers.produce.quota(clientId)
+      val overrideConsumerQuota = quotaManagers.fetch.quota(clientId)
 
       assertEquals(s"ClientId $clientId must have overridden producer quota of 1000",
         Quota.upperBound(1000), overrideProducerQuota)
-        assertEquals(s"ClientId $clientId must have overridden consumer quota of 2000",
+      assertEquals(s"ClientId $clientId must have overridden consumer quota of 2000",
         Quota.upperBound(2000), overrideConsumerQuota)
     }
 
@@ -84,8 +84,8 @@ class DynamicConfigChangeTest extends KafkaServerTestHarness {
     AdminUtils.changeClientIdConfig(zkUtils, clientId, new Properties())
 
     TestUtils.retry(10000) {
-      val producerQuota = quotaManagers.get(ApiKeys.PRODUCE.id).get.quota(clientId)
-      val consumerQuota = quotaManagers.get(ApiKeys.FETCH.id).get.quota(clientId)
+      val producerQuota = quotaManagers.produce.quota(clientId)
+      val consumerQuota = quotaManagers.fetch.quota(clientId)
 
       assertEquals(s"ClientId $clientId must have reset producer quota to " + defaultProducerQuota,
         Quota.upperBound(defaultProducerQuota), producerQuota)
@@ -99,7 +99,7 @@ class DynamicConfigChangeTest extends KafkaServerTestHarness {
     val topic = TestUtils.tempTopic
     try {
       val logProps = new Properties()
-      logProps.put(LogConfig.FlushMessagesProp, 10000: java.lang.Integer)
+      logProps.put(FlushMessagesProp, 10000: java.lang.Integer)
       AdminUtils.changeTopicConfig(zkUtils, topic, logProps)
       fail("Should fail with AdminOperationException for topic doesn't exist")
     } catch {
@@ -162,4 +162,47 @@ class DynamicConfigChangeTest extends KafkaServerTestHarness {
     // Verify that processConfigChanges was only called once
     EasyMock.verify(handler)
   }
-}
+
+  @Test
+  def shouldParseReplicationQuotaProperties {
+    val configHandler: TopicConfigHandler = new TopicConfigHandler(null, null, null)
+    val props: Properties = new Properties()
+
+    //Given
+    props.put(ThrottledReplicasListProp, "0:101,0:102,1:101,1:102")
+
+    //When/Then
+    assertEquals(Seq(0,1), configHandler.parseThrottledPartitions(props, 102))
+    assertEquals(Seq(), configHandler.parseThrottledPartitions(props, 103))
+  }
+
+  @Test
+  def shouldParseWildcardReplicationQuotaProperties {
+    val configHandler: TopicConfigHandler = new TopicConfigHandler(null, null, null)
+    val props: Properties = new Properties()
+
+    //Given
+    props.put(ThrottledReplicasListProp, "*")
+
+    //When
+    val result = configHandler.parseThrottledPartitions(props, 102)
+
+    //Then
+    assertEquals(AllReplicas, result)
+  }
+
+  @Test
+  def shouldParseReplicationQuotaReset {
+    val configHandler: TopicConfigHandler = new TopicConfigHandler(null, null, null)
+    val props: Properties = new Properties()
+
+    //Given
+    props.put(ThrottledReplicasListProp, "")
+
+    //When
+    val result = configHandler.parseThrottledPartitions(props, 102)
+
+    //Then
+    assertEquals(Seq(), result)
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala b/core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala
index f5b515b..e7e1554 100755
--- a/core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala
+++ b/core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala
@@ -18,14 +18,15 @@ package kafka.server
 
 import kafka.log._
 import java.io.File
+import kafka.utils.SystemTime
 import org.apache.kafka.common.metrics.Metrics
-import org.apache.kafka.common.utils.{Utils, MockTime => JMockTime}
+import org.apache.kafka.common.utils.{MockTime => JMockTime, Utils}
 import org.easymock.EasyMock
 import org.junit._
 import org.junit.Assert._
 import kafka.common._
 import kafka.cluster.Replica
-import kafka.utils.{KafkaScheduler, MockTime, SystemTime, TestUtils, ZkUtils}
+import kafka.utils.{KafkaScheduler, MockTime, TestUtils, ZkUtils}
 import java.util.concurrent.atomic.AtomicBoolean
 
 class HighwatermarkPersistenceTest {
@@ -56,7 +57,7 @@ class HighwatermarkPersistenceTest {
     val metrics = new Metrics
     // create replica manager
     val replicaManager = new ReplicaManager(configs.head, metrics, new MockTime, new JMockTime, zkUtils, scheduler,
-      logManagers.head, new AtomicBoolean(false))
+      logManagers.head, new AtomicBoolean(false), QuotaFactory.instantiate(configs.head, metrics, SystemTime).follower)
     replicaManager.startup()
     try {
       replicaManager.checkpointHighWatermarks()
@@ -99,7 +100,7 @@ class HighwatermarkPersistenceTest {
     val metrics = new Metrics
     // create replica manager
     val replicaManager = new ReplicaManager(configs.head, metrics, new MockTime(), new JMockTime, zkUtils,
-      scheduler, logManagers.head, new AtomicBoolean(false))
+      scheduler, logManagers.head, new AtomicBoolean(false), QuotaFactory.instantiate(configs.head, metrics, SystemTime).follower)
     replicaManager.startup()
     try {
       replicaManager.checkpointHighWatermarks()

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ISRExpirationTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ISRExpirationTest.scala b/core/src/test/scala/unit/kafka/server/ISRExpirationTest.scala
index c34e4f0..540a665 100644
--- a/core/src/test/scala/unit/kafka/server/ISRExpirationTest.scala
+++ b/core/src/test/scala/unit/kafka/server/ISRExpirationTest.scala
@@ -52,7 +52,7 @@ class IsrExpirationTest {
 
   @Before
   def setUp() {
-    replicaManager = new ReplicaManager(configs.head, metrics, time, jTime, null, null, null, new AtomicBoolean(false))
+    replicaManager = new ReplicaManager(configs.head, metrics, time, jTime, null, null, null, new AtomicBoolean(false), QuotaFactory.instantiate(configs.head, metrics, SystemTime).follower)
   }
 
   @After

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ReplicaManagerQuotasTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ReplicaManagerQuotasTest.scala b/core/src/test/scala/unit/kafka/server/ReplicaManagerQuotasTest.scala
new file mode 100644
index 0000000..69365aa
--- /dev/null
+++ b/core/src/test/scala/unit/kafka/server/ReplicaManagerQuotasTest.scala
@@ -0,0 +1,154 @@
+/**
+  * 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.
+  */
+package kafka.server
+
+
+import java.util.Properties
+import java.util.concurrent.atomic.AtomicBoolean
+
+import kafka.api._
+import kafka.cluster.Replica
+import kafka.common.TopicAndPartition
+import kafka.log.Log
+import kafka.message.{ByteBufferMessageSet, Message}
+import kafka.utils._
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.utils.{MockTime => JMockTime}
+import org.easymock.EasyMock
+import org.easymock.EasyMock._
+import org.junit.Assert._
+import org.junit.{After, Test}
+
+
+class ReplicaManagerQuotasTest {
+  val configs = TestUtils.createBrokerConfigs(2, TestUtils.MockZkConnect).map(KafkaConfig.fromProps(_, new Properties()))
+  val time = new MockTime
+  val jTime = new JMockTime
+  val metrics = new Metrics
+  val message = new Message("some-data-in-a-message".getBytes())
+  val topicAndPartition1 = TopicAndPartition("test-topic", 1)
+  val topicAndPartition2 = TopicAndPartition("test-topic", 2)
+  val fetchInfo = Map(topicAndPartition1 -> PartitionFetchInfo(0, 100), topicAndPartition2 -> PartitionFetchInfo(0, 100))
+  var replicaManager: ReplicaManager = null
+
+  @Test
+  def shouldExcludeSubsequentThrottledPartitions(): Unit = {
+    setUpMocks(fetchInfo)
+
+    val quota = mockQuota(1000000)
+    expect(quota.isQuotaExceeded()).andReturn(false).once()
+    expect(quota.isQuotaExceeded()).andReturn(true).once()
+    replay(quota)
+
+    val fetch = replicaManager.readFromLocalLog(true, true, fetchInfo, quota)
+    assertEquals("Given two partitions, with only one throttled, we should get the first", 1,
+      fetch.get(topicAndPartition1).get.info.messageSet.size)
+
+    assertEquals("But we shouldn't get the second", 0,
+      fetch.get(topicAndPartition2).get.info.messageSet.size)
+  }
+
+  @Test
+  def shouldGetNoMessagesIfQuotasExceededOnSubsequentPartitions(): Unit = {
+    setUpMocks(fetchInfo)
+
+    val quota = mockQuota(1000000)
+    expect(quota.isQuotaExceeded()).andReturn(true).once()
+    expect(quota.isQuotaExceeded()).andReturn(true).once()
+    replay(quota)
+
+    val fetch = replicaManager.readFromLocalLog(true, true, fetchInfo, quota)
+    assertEquals("Given two partitions, with both throttled, we should get no messages", 0,
+      fetch.get(topicAndPartition1).get.info.messageSet.size)
+    assertEquals("Given two partitions, with both throttled, we should get no messages", 0,
+      fetch.get(topicAndPartition2).get.info.messageSet.size)
+  }
+
+  @Test
+  def shouldGetBothMessagesIfQuotasAllow(): Unit = {
+    setUpMocks(fetchInfo)
+
+    val quota = mockQuota(1000000)
+    expect(quota.isQuotaExceeded()).andReturn(false).once()
+    expect(quota.isQuotaExceeded()).andReturn(false).once()
+    replay(quota)
+
+    val fetch = replicaManager.readFromLocalLog(true, true, fetchInfo, quota)
+    assertEquals("Given two partitions, with both non-throttled, we should get both messages", 1,
+      fetch.get(topicAndPartition1).get.info.messageSet.size)
+    assertEquals("Given two partitions, with both non-throttled, we should get both messages", 1,
+      fetch.get(topicAndPartition2).get.info.messageSet.size)
+  }
+
+  def setUpMocks(fetchInfo: Map[TopicAndPartition, PartitionFetchInfo], message: Message = this.message) {
+    val zkUtils = createNiceMock(classOf[ZkUtils])
+    val scheduler = createNiceMock(classOf[KafkaScheduler])
+
+    //Create log which handles both a regular read and a 0 bytes read
+    val log = createMock(classOf[Log])
+    expect(log.logEndOffset).andReturn(20L).anyTimes()
+    expect(log.logEndOffsetMetadata).andReturn(new LogOffsetMetadata(20L)).anyTimes()
+
+    //if we ask for len 1 return a message
+    expect(log.read(anyObject(), geq(1), anyObject())).andReturn(
+      new FetchDataInfo(
+        new LogOffsetMetadata(0L, 0L, 0),
+        new ByteBufferMessageSet(message)
+      )).anyTimes()
+
+    //if we ask for len = 0, return 0 messages
+    expect(log.read(anyObject(), EasyMock.eq(0), anyObject())).andReturn(
+      new FetchDataInfo(
+        new LogOffsetMetadata(0L, 0L, 0),
+        new ByteBufferMessageSet()
+      )).anyTimes()
+    replay(log)
+
+    //Create log manager
+    val logManager = createMock(classOf[kafka.log.LogManager])
+
+    //Return the same log for each partition as it doesn't matter
+    expect(logManager.getLog(anyObject())).andReturn(Some(log)).anyTimes()
+    replay(logManager)
+
+    replicaManager = new ReplicaManager(configs.head, metrics, time, jTime, zkUtils, scheduler, logManager,
+      new AtomicBoolean(false), QuotaFactory.instantiate(configs.head, metrics, time).follower)
+
+    //create the two replicas
+    for (p <- fetchInfo.keySet) {
+      val partition = replicaManager.getOrCreatePartition(p.topic, p.partition)
+      val replica = new Replica(configs.head.brokerId, partition, time, 0, Some(log))
+      replica.highWatermark = new LogOffsetMetadata(5)
+      partition.leaderReplicaIdOpt = Some(replica.brokerId)
+      val allReplicas = List(replica)
+      allReplicas.foreach(partition.addReplicaIfNotExists(_))
+      partition.inSyncReplicas = allReplicas.toSet
+    }
+  }
+
+  @After
+  def tearDown() {
+    replicaManager.shutdown(false)
+    metrics.close()
+  }
+
+  def mockQuota(bound: Long): ReplicaQuota = {
+    val quota = createMock(classOf[ReplicaQuota])
+    expect(quota.isThrottled(anyObject())).andReturn(true).anyTimes()
+    quota
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ReplicaManagerTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ReplicaManagerTest.scala b/core/src/test/scala/unit/kafka/server/ReplicaManagerTest.scala
index bfb66b9..47e5461 100644
--- a/core/src/test/scala/unit/kafka/server/ReplicaManagerTest.scala
+++ b/core/src/test/scala/unit/kafka/server/ReplicaManagerTest.scala
@@ -66,7 +66,7 @@ class ReplicaManagerTest {
     val config = KafkaConfig.fromProps(props)
     val mockLogMgr = TestUtils.createLogManager(config.logDirs.map(new File(_)).toArray)
     val rm = new ReplicaManager(config, metrics, time, jTime, zkUtils, new MockScheduler(time), mockLogMgr,
-      new AtomicBoolean(false))
+      new AtomicBoolean(false), QuotaFactory.instantiate(config, metrics, time).follower)
     try {
       val partition = rm.getOrCreatePartition(topic, 1)
       partition.getOrCreateReplica(1)
@@ -84,7 +84,7 @@ class ReplicaManagerTest {
     val config = KafkaConfig.fromProps(props)
     val mockLogMgr = TestUtils.createLogManager(config.logDirs.map(new File(_)).toArray)
     val rm = new ReplicaManager(config, metrics, time, jTime, zkUtils, new MockScheduler(time), mockLogMgr,
-      new AtomicBoolean(false))
+      new AtomicBoolean(false), QuotaFactory.instantiate(config, metrics, time).follower)
     try {
       val partition = rm.getOrCreatePartition(topic, 1)
       partition.getOrCreateReplica(1)
@@ -101,7 +101,7 @@ class ReplicaManagerTest {
     val config = KafkaConfig.fromProps(props)
     val mockLogMgr = TestUtils.createLogManager(config.logDirs.map(new File(_)).toArray)
     val rm = new ReplicaManager(config, metrics, time, jTime, zkUtils, new MockScheduler(time), mockLogMgr,
-      new AtomicBoolean(false), Option(this.getClass.getName))
+      new AtomicBoolean(false), QuotaFactory.instantiate(config, metrics, time).follower, Option(this.getClass.getName))
     try {
       def callback(responseStatus: Map[TopicPartition, PartitionResponse]) = {
         assert(responseStatus.values.head.errorCode == Errors.INVALID_REQUIRED_ACKS.code)
@@ -126,7 +126,7 @@ class ReplicaManagerTest {
     val config = KafkaConfig.fromProps(props)
     val mockLogMgr = TestUtils.createLogManager(config.logDirs.map(new File(_)).toArray)
     val rm = new ReplicaManager(config, metrics, time, jTime, zkUtils, new MockScheduler(time), mockLogMgr,
-      new AtomicBoolean(false))
+      new AtomicBoolean(false), QuotaFactory.instantiate(config, metrics, time).follower)
 
     try {
       var produceCallbackFired = false
@@ -195,7 +195,7 @@ class ReplicaManagerTest {
     val config = KafkaConfig.fromProps(props)
     val mockLogMgr = TestUtils.createLogManager(config.logDirs.map(new File(_)).toArray)
     val rm = new ReplicaManager(config, metrics, time, jTime, zkUtils, new MockScheduler(time), mockLogMgr,
-      new AtomicBoolean(false), Option(this.getClass.getName))
+      new AtomicBoolean(false), QuotaFactory.instantiate(config, metrics, time).follower, Option(this.getClass.getName))
     try {
       val aliveBrokers = Seq(new Broker(0, "host0", 0), new Broker(1, "host1", 1), new Broker(1, "host2", 2))
       val metadataCache = EasyMock.createMock(classOf[MetadataCache])

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ReplicationQuotaManagerTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ReplicationQuotaManagerTest.scala b/core/src/test/scala/unit/kafka/server/ReplicationQuotaManagerTest.scala
new file mode 100644
index 0000000..5c41372
--- /dev/null
+++ b/core/src/test/scala/unit/kafka/server/ReplicationQuotaManagerTest.scala
@@ -0,0 +1,123 @@
+/**
+  * 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.
+  */
+package unit.kafka.server
+
+import java.util.Collections
+
+import kafka.common.TopicAndPartition
+import kafka.server.QuotaType._
+import kafka.server.{QuotaType, ReplicationQuotaManager, ReplicationQuotaManagerConfig}
+import org.apache.kafka.common.metrics.{Quota, MetricConfig, Metrics}
+import org.apache.kafka.common.utils.MockTime
+import org.junit.Assert.{assertFalse, assertTrue, assertEquals}
+import org.junit.Test
+import scala.collection.JavaConverters._
+
+class ReplicationQuotaManagerTest {
+  private val time = new MockTime
+
+  @Test
+  def shouldThrottleOnlyDefinedReplicas() {
+    val quota = new ReplicationQuotaManager(ReplicationQuotaManagerConfig(), newMetrics, QuotaType.Fetch, time)
+    quota.markThrottled("topic1", Seq(1, 2, 3))
+
+    assertTrue(quota.isThrottled(tp1(1)))
+    assertTrue(quota.isThrottled(tp1(2)))
+    assertTrue(quota.isThrottled(tp1(3)))
+    assertFalse(quota.isThrottled(tp1(4)))
+  }
+
+  @Test
+  def shouldExceedQuotaThenReturnBackBelowBoundAsTimePasses(): Unit = {
+    val metrics = newMetrics()
+    val quota = new ReplicationQuotaManager(ReplicationQuotaManagerConfig(numQuotaSamples = 10, quotaWindowSizeSeconds = 1), metrics, LeaderReplication, time)
+
+    //Given
+    quota.updateQuota(new Quota(100, true))
+
+    //Quota should not be broken when we start
+    assertFalse(quota.isQuotaExceeded())
+
+    //First window is fixed, so we'll skip it
+    time.sleep(1000)
+
+    //When we record up to the quota value after half a window
+    time.sleep(500)
+    quota.record(1)
+
+    //Then it should not break the quota
+    assertFalse(quota.isQuotaExceeded())
+
+    //When we record half the quota (half way through the window), we still should not break
+    quota.record(149) //150B, 1.5s
+    assertFalse(quota.isQuotaExceeded())
+
+    //Add a byte to push over quota
+    quota.record(1) //151B, 1.5s
+
+    //Then it should break the quota
+    assertEquals(151 / 1.5, rate(metrics), 0) //151B, 1.5s
+    assertTrue(quota.isQuotaExceeded())
+
+    //When we sleep for the remaining half the window
+    time.sleep(500) //151B, 2s
+
+    //Then Our rate should have halved (i.e back down below the quota)
+    assertFalse(quota.isQuotaExceeded())
+    assertEquals(151d / 2, rate(metrics), 0.1) //151B, 2s
+
+    //When we sleep for another half a window (now half way through second window)
+    time.sleep(500)
+    quota.record(99) //250B, 2.5s
+
+    //Then the rate should be exceeded again
+    assertEquals(250 / 2.5, rate(metrics), 0) //250B, 2.5s
+    assertFalse(quota.isQuotaExceeded())
+    quota.record(1)
+    assertTrue(quota.isQuotaExceeded())
+    assertEquals(251 / 2.5, rate(metrics), 0)
+
+    //Sleep for 2 more window
+    time.sleep(2 * 1000) //so now at 3.5s
+    assertFalse(quota.isQuotaExceeded())
+    assertEquals(251d / 4.5, rate(metrics), 0)
+  }
+
+  def rate(metrics: Metrics): Double = {
+    val metricName = metrics.metricName("byte-rate", LeaderReplication.toString, "Tracking byte-rate for " + LeaderReplication)
+    val leaderThrottledRate = metrics.metrics.asScala(metricName).value()
+    leaderThrottledRate
+  }
+
+  @Test
+  def shouldSupportWildcardThrottledReplicas(): Unit = {
+    val quota = new ReplicationQuotaManager(ReplicationQuotaManagerConfig(), newMetrics, LeaderReplication, time)
+
+    //When
+    quota.markThrottled("MyTopic")
+
+    //Then
+    assertTrue(quota.isThrottled(TopicAndPartition("MyTopic", 0)))
+    assertFalse(quota.isThrottled(TopicAndPartition("MyOtherTopic", 0)))
+  }
+
+  private def tp1(id: Int): TopicAndPartition = new TopicAndPartition("topic1", id)
+
+  private def newMetrics(): Metrics = {
+    new Metrics(new MetricConfig(), Collections.emptyList(), time)
+  }
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ReplicationQuotasTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ReplicationQuotasTest.scala b/core/src/test/scala/unit/kafka/server/ReplicationQuotasTest.scala
new file mode 100644
index 0000000..af7c4c8
--- /dev/null
+++ b/core/src/test/scala/unit/kafka/server/ReplicationQuotasTest.scala
@@ -0,0 +1,242 @@
+/**
+  * 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.
+  */
+
+package unit.kafka.server
+
+import java.util.Properties
+
+import kafka.admin.AdminUtils
+import kafka.admin.AdminUtils._
+import kafka.common._
+import kafka.log.LogConfig._
+import kafka.server.KafkaConfig.fromProps
+import kafka.server.QuotaType._
+import kafka.server._
+import kafka.utils.TestUtils
+import kafka.utils.TestUtils._
+import kafka.zk.ZooKeeperTestHarness
+import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
+import org.junit.Assert._
+import org.junit.{After, Before, Test}
+import scala.collection.JavaConverters._
+
+/**
+  * This is the main test which ensure Replication Quotas work correctly.
+  *
+  * The test will fail if the quota is < 1MB/s as 1MB is the default for replica.fetch.max.bytes.
+  * So with a throttle of 100KB/s, 1 fetch of 1 partition would fill 10s of quota. In turn causing
+  * the throttled broker to pause for > 10s
+  *
+  * Anything over 100MB/s tends to fail as this is the non-throttled replication rate
+  */
+
+class ReplicationQuotasTest extends ZooKeeperTestHarness {
+  def percentError(percent: Int, value: Long): Long = Math.round(value * percent / 100)
+
+  val msg100KB = new Array[Byte](100000)
+  var brokers: Seq[KafkaServer] = null
+  val topic = "topic1"
+  var producer: KafkaProducer[Array[Byte], Array[Byte]] = null
+
+  @Before
+  override def setUp() {
+    super.setUp()
+  }
+
+  @After
+  override def tearDown() {
+    brokers.par.foreach(_.shutdown())
+    producer.close()
+    super.tearDown()
+  }
+
+  @Test
+  def shouldBootstrapTwoBrokersWithLeaderThrottle(): Unit = {
+    shouldMatchQuotaReplicatingThroughAnAsymmetricTopology(true)
+  }
+
+  @Test
+  def shouldBootstrapTwoBrokersWithFollowerThrottle(): Unit = {
+    shouldMatchQuotaReplicatingThroughAnAsymmetricTopology(false)
+  }
+
+  def shouldMatchQuotaReplicatingThroughAnAsymmetricTopology(leaderThrottle: Boolean): Unit = {
+    /**
+      * In short we have 8 brokers, 2 are not-started. We assign replicas for the two non-started
+      * brokers, so when we start them we can monitor replication from the 6 to the 2.
+      *
+      * We also have two non-throttled partitions on two of the 6 brokers, just to make sure
+      * regular replication works as expected.
+      */
+
+    brokers = (100 to 105).map { id => TestUtils.createServer(fromProps(createBrokerConfig(id, zkConnect))) }
+
+    //Given six partitions, lead on nodes 0,1,2,3,4,5 but will followers on node 6,7 (not started yet)
+    //And two extra partitions 6,7, which we don't intend on throttling
+    AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(zkUtils, topic, Map(
+      0 -> Seq(100, 106), //Throttled
+      1 -> Seq(101, 106), //Throttled
+      2 -> Seq(102, 106), //Throttled
+      3 -> Seq(103, 107), //Throttled
+      4 -> Seq(104, 107), //Throttled
+      5 -> Seq(105, 107), //Throttled
+      6 -> Seq(100, 106), //Not Throttled
+      7 -> Seq(101, 107) //Not Throttled
+    ))
+
+    val msg = msg100KB
+    val msgCount: Int = 1000
+    val expectedDuration = 10 //Keep the test to N seconds
+    var throttle: Long = msgCount * msg.length / expectedDuration
+    if (!leaderThrottle) throttle = throttle * 3 //Follower throttle needs to replicate 3x as fast to get the same duration as there are three replicas to replicate for each of the two follower brokers
+
+    //Set the throttle limit on all 8 brokers, but only assign throttled replicas to the six leaders, or two followers
+    (100 to 107).foreach { brokerId =>
+      changeBrokerConfig(zkUtils, Seq(brokerId), property(KafkaConfig.ThrottledReplicationRateLimitProp, throttle.toString))
+    }
+    if (leaderThrottle)
+      changeTopicConfig(zkUtils, topic, property(ThrottledReplicasListProp, "0:100,1:101,2:102,3:103,4:104,5:105")) //partition-broker:... throttle the 6 leaders
+    else
+      changeTopicConfig(zkUtils, topic, property(ThrottledReplicasListProp, "0:106,1:106,2:106,3:107,4:107,5:107")) //partition-broker:... throttle the two followers
+
+    //Add data equally to each partition
+    producer = TestUtils.createNewProducer(TestUtils.getBrokerListStrFromServers(brokers), retries = 5, acks = 0)
+    (0 until msgCount).foreach { x =>
+      (0 to 7).foreach { partition =>
+        producer.send(new ProducerRecord(topic, partition, null, msg)).get
+      }
+    }
+
+    //Ensure data is fully written: broker 1 has partition 1, broker 2 has partition 2 etc
+    (0 to 5).foreach { id => waitForOffsetsToMatch(msgCount, id, 100 + id) }
+    //Check the non-throttled partitions too
+    waitForOffsetsToMatch(msgCount, 6, 100)
+    waitForOffsetsToMatch(msgCount, 7, 101)
+
+    val start = System.currentTimeMillis()
+
+    //When we create the 2 new, empty brokers
+    brokers = brokers :+ TestUtils.createServer(fromProps(createBrokerConfig(106, zkConnect)))
+    brokers = brokers :+ TestUtils.createServer(fromProps(createBrokerConfig(107, zkConnect)))
+
+    //Check that throttled config correctly migrated to the new brokers
+    (106 to 107).foreach { brokerId =>
+      assertEquals(throttle, brokerFor(brokerId).quotaManagers.follower.upperBound())
+    }
+    if (!leaderThrottle) {
+      (0 to 2).foreach { partition =>
+        assertTrue(brokerFor(106).quotaManagers.follower.isThrottled(new TopicAndPartition(topic, partition)))
+      }
+      (3 to 5).foreach { partition =>
+        assertTrue(brokerFor(107).quotaManagers.follower.isThrottled(new TopicAndPartition(topic, partition)))
+      }
+    }
+
+    //Wait for non-throttled partitions to replicate first
+    (6 to 7).foreach { id => waitForOffsetsToMatch(msgCount, id, 100 + id) }
+    val unthrottledTook = System.currentTimeMillis() - start
+
+    //Wait for replicas 0,1,2,3,4,5 to fully replicated to broker 106,107
+    (0 to 2).foreach { id => waitForOffsetsToMatch(msgCount, id, 106) }
+    (3 to 5).foreach { id => waitForOffsetsToMatch(msgCount, id, 107) }
+
+    val throttledTook = System.currentTimeMillis() - start
+
+    //Check the recorded throttled rate is what we expect
+    if (leaderThrottle) {
+      (100 to 105).map(brokerFor(_)).foreach { broker =>
+        val metricName = broker.metrics.metricName("byte-rate", LeaderReplication.toString, "Tracking byte-rate for" + LeaderReplication)
+        val measuredRate = broker.metrics.metrics.asScala(metricName).value()
+        info(s"Broker:${broker.config.brokerId} Expected:$throttle, Recorded Rate was:$measuredRate")
+        assertEquals(throttle, measuredRate, percentError(25, throttle))
+      }
+    } else {
+      (106 to 107).map(brokerFor(_)).foreach { broker =>
+        val metricName = broker.metrics.metricName("byte-rate", FollowerReplication.toString, "Tracking byte-rate for" + FollowerReplication)
+        val measuredRate = broker.metrics.metrics.asScala(metricName).value()
+        info(s"Broker:${broker.config.brokerId} Expected:$throttle, Recorded Rate was:$measuredRate")
+        assertEquals(throttle, measuredRate, percentError(25, throttle))
+      }
+    }
+
+    //Check the times for throttled/unthrottled are each side of what we expect
+    info(s"Unthrottled took: $unthrottledTook, Throttled took: $throttledTook, for expeted $expectedDuration secs")
+    assertTrue(s"Unthrottled replication of ${unthrottledTook}ms should be < ${expectedDuration * 1000}ms",
+      unthrottledTook < expectedDuration * 1000)
+    assertTrue((s"Throttled replication of ${throttledTook}ms should be > ${expectedDuration * 1000}ms"),
+      throttledTook > expectedDuration * 1000)
+    assertTrue((s"Throttled replication of ${throttledTook}ms should be < ${expectedDuration * 1500}ms"),
+      throttledTook < expectedDuration * 1000 * 1.5)
+  }
+
+  @Test
+  def shouldThrottleOldSegments(): Unit = {
+    /**
+      * Simple test which ensures throttled replication works when the dataset spans many segments
+      */
+
+    //2 brokers with 1MB Segment Size & 1 partition
+    val config: Properties = createBrokerConfig(100, zkConnect)
+    config.put("log.segment.bytes", (1024 * 1024).toString)
+    brokers = Seq(TestUtils.createServer(fromProps(config)))
+    AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(zkUtils, topic, Map(0 -> Seq(100, 101)))
+
+    //Write 20MBs and throttle at 5MB/s
+    val msg = msg100KB
+    val msgCount: Int = 200
+    val expectedDuration = 4
+    val throttle: Long = msg.length * msgCount / expectedDuration
+
+    //Set the throttle limit leader
+    changeBrokerConfig(zkUtils, Seq(100), property(KafkaConfig.ThrottledReplicationRateLimitProp, throttle.toString))
+    changeTopicConfig(zkUtils, topic, property(ThrottledReplicasListProp, "0:100"))
+
+    //Add data
+    addData(msgCount, msg)
+
+    val start = System.currentTimeMillis()
+
+    //Start the new broker (and hence start replicating)
+    brokers = brokers :+ TestUtils.createServer(fromProps(createBrokerConfig(101, zkConnect)))
+    waitForOffsetsToMatch(msgCount, 0, 101)
+
+    val throttledTook = System.currentTimeMillis() - start
+
+    assertTrue((s"Throttled replication of ${throttledTook}ms should be > ${expectedDuration * 1000 * 0.9}ms"),
+      throttledTook > expectedDuration * 1000 * 0.9)
+    assertTrue((s"Throttled replication of ${throttledTook}ms should be < ${expectedDuration * 1500}ms"),
+      throttledTook < expectedDuration * 1000 * 1.5)
+  }
+
+  def addData(msgCount: Int, msg: Array[Byte]): Boolean = {
+    producer = TestUtils.createNewProducer(TestUtils.getBrokerListStrFromServers(brokers), retries = 5, acks = 0)
+    (0 until msgCount).foreach { x => producer.send(new ProducerRecord(topic, msg)).get }
+    waitForOffsetsToMatch(msgCount, 0, 100)
+  }
+
+  private def waitForOffsetsToMatch(offset: Int, partitionId: Int, brokerId: Int): Boolean = {
+    waitUntilTrue(() => {
+      offset == brokerFor(brokerId).getLogManager.getLog(TopicAndPartition(topic, partitionId)).map(_.logEndOffset).getOrElse(0)
+    }, s"Offsets did not match for partition $partitionId on broker $brokerId", 60000)
+  }
+
+  private def property(key: String, value: String) = {
+    new Properties() { put(key, value) }
+  }
+
+  private def brokerFor(id: Int): KafkaServer = brokers.filter(_.config.brokerId == id)(0)
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/SimpleFetchTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/SimpleFetchTest.scala b/core/src/test/scala/unit/kafka/server/SimpleFetchTest.scala
index 7741698..1052be5 100644
--- a/core/src/test/scala/unit/kafka/server/SimpleFetchTest.scala
+++ b/core/src/test/scala/unit/kafka/server/SimpleFetchTest.scala
@@ -16,23 +16,23 @@
  */
 package kafka.server
 
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.{Collections, Properties}
+
 import kafka.api._
-import kafka.utils._
 import kafka.cluster.Replica
 import kafka.common.TopicAndPartition
 import kafka.log.Log
-import kafka.message.{MessageSet, ByteBufferMessageSet, Message}
+import kafka.message.{ByteBufferMessageSet, Message, MessageSet}
+import kafka.server.QuotaFactory.UnboundedQuota
+import kafka.utils._
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.utils.{MockTime => JMockTime}
-import org.junit.{Test, After, Before}
-
-import java.util.{Properties, Collections}
-import java.util.concurrent.atomic.AtomicBoolean
-import collection.JavaConversions._
-
 import org.easymock.EasyMock
-import org.I0Itec.zkclient.ZkClient
 import org.junit.Assert._
+import org.junit.{After, Before, Test}
+
+import scala.collection.JavaConversions._
 
 class SimpleFetchTest {
 
@@ -99,7 +99,7 @@ class SimpleFetchTest {
 
     // create the replica manager
     replicaManager = new ReplicaManager(configs.head, metrics, time, jTime, zkUtils, scheduler, logManager,
-      new AtomicBoolean(false))
+      new AtomicBoolean(false), QuotaFactory.instantiate(configs.head, metrics, time).follower)
 
     // add the partition with two replicas, both in ISR
     val partition = replicaManager.getOrCreatePartition(topic, partitionId)
@@ -148,9 +148,9 @@ class SimpleFetchTest {
     val initialAllTopicsCount = BrokerTopicStats.getBrokerAllTopicsStats().totalFetchRequestRate.count()
 
     assertEquals("Reading committed data should return messages only up to high watermark", messagesToHW,
-      replicaManager.readFromLocalLog(true, true, fetchInfo).get(topicAndPartition).get.info.messageSet.head.message)
+      replicaManager.readFromLocalLog(true, true, fetchInfo, UnboundedQuota).get(topicAndPartition).get.info.messageSet.head.message)
     assertEquals("Reading any data can return messages up to the end of the log", messagesToLEO,
-      replicaManager.readFromLocalLog(true, false, fetchInfo).get(topicAndPartition).get.info.messageSet.head.message)
+      replicaManager.readFromLocalLog(true, false, fetchInfo, UnboundedQuota).get(topicAndPartition).get.info.messageSet.head.message)
 
     assertEquals("Counts should increment after fetch", initialTopicCount+2, BrokerTopicStats.getBrokerTopicStats(topic).totalFetchRequestRate.count())
     assertEquals("Counts should increment after fetch", initialAllTopicsCount+2, BrokerTopicStats.getBrokerAllTopicsStats().totalFetchRequestRate.count())

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/ThrottledResponseExpirationTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/ThrottledResponseExpirationTest.scala b/core/src/test/scala/unit/kafka/server/ThrottledResponseExpirationTest.scala
index 778f3f8..aae66d8 100644
--- a/core/src/test/scala/unit/kafka/server/ThrottledResponseExpirationTest.scala
+++ b/core/src/test/scala/unit/kafka/server/ThrottledResponseExpirationTest.scala
@@ -43,7 +43,7 @@ class ThrottledResponseExpirationTest {
 
   @Test
   def testExpire() {
-    val clientMetrics = new ClientQuotaManager(ClientQuotaManagerConfig(), metrics, "producer", time)
+    val clientMetrics = new ClientQuotaManager(ClientQuotaManagerConfig(), metrics, QuotaType.Produce, time)
 
     val delayQueue = new DelayQueue[ThrottledResponse]()
     val reaper = new clientMetrics.ThrottledRequestReaper(delayQueue)

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/utils/TestUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/utils/TestUtils.scala b/core/src/test/scala/unit/kafka/utils/TestUtils.scala
index 131a24a..dadc8a3 100755
--- a/core/src/test/scala/unit/kafka/utils/TestUtils.scala
+++ b/core/src/test/scala/unit/kafka/utils/TestUtils.scala
@@ -933,18 +933,24 @@ object TestUtils extends Logging {
 
   def produceMessages(servers: Seq[KafkaServer],
                       topic: String,
-                      numMessages: Int): Seq[String] = {
+                      numMessages: Int,
+                      acks: Int = 0,
+                      valueBytes: Int = -1): Seq[Array[Byte]] = {
 
     val producer = createNewProducer(
       TestUtils.getBrokerListStrFromServers(servers),
       retries = 5,
-      requestTimeoutMs = 2000
+      requestTimeoutMs = 2000,
+      acks = acks
     )
 
-    val values = (0 until numMessages).map(x => s"test-$x")
+    val values = (0 until numMessages).map(x => valueBytes match {
+      case -1 => s"test-$x".getBytes
+      case _ => new Array[Byte](valueBytes)
+    })
     
     val futures = values.map { value =>
-      producer.send(new ProducerRecord(topic, null, null, value.getBytes))
+      producer.send(new ProducerRecord(topic, value))
     }
     futures.foreach(_.get)
     producer.close()


[3/3] kafka git commit: KAFKA-1464; Add a throttling option to the Kafka replication

Posted by ju...@apache.org.
KAFKA-1464; Add a throttling option to the Kafka replication

This applies to Replication Quotas
based on KIP-73 [(link)](https://cwiki.apache.org/confluence/display/KAFKA/KIP-73+Replication+Quotas) originally motivated by KAFKA-1464.

System Tests Run: https://jenkins.confluent.io/job/system-test-kafka-branch-builder/544/

**This first PR demonstrates the approach**.

**_Overview of Change_**
The guts of this change are relatively small. Throttling occurs on both leader and follower sides. A single class tracks the throttled throughput in and out of each broker (**_ReplicationQuotaManager_**).

On the follower side, the Follower Throttled Rate is calculated as fetch responses arrive. Then, before the next fetch request is sent, we check to see if the quota is violated, removing throttled partitions from the request if it is. This is all encapsulated in a few lines of code in the **_ReplicaFetcherThread_**. There is existing code to handle temporal back off, if the request ends up being empty.

On the leader side it's a little more complex. When a fetch request arrives in the leader, it is built, partition by partition, in **_ReplicaManager.readFromLocalLog_**. As we put each partition into the fetch response, we check if the total size fits in the current quota. If the quota is exceeded, the partition will not be added to the fetch response. Importantly, we don't increase the quota at this point, we just check to see if the bytes will fit.

Now, if there aren't enough bytes to send the response immediately, which is common if we're catching up and throttled, then the request will be put in purgatory. I've added some simple code to **_DelayedFetch_** to handle throttled partitions (throttled partitions are checked against the quota, rather than the messages available in the log).

When the delayed fetch completes, and exits purgatory, _**ReplicaManager.readFromLocalLog**_ will be called again. This is why _**ReplicaManager.readFromLocalLog**_ does not actually increase the quota, it just checks whether enough bytes are available for a partition.

Finally, when there are enough bytes to be sent, or the delayed fetch times out, the response will be sent. Before it is sent the throttled-outbound-rate is increased, based on the size of throttled partitions being sent. This is at the end of _**KafkaApis.handleFetchRequest**_, exactly where client quotas are recorded.

There is an acceptance test which asserts the whole throttling process stabilises on the desired value. This covers a number of use cases including many-to-many replication. See **_ReplicationQuotaTest_**.

Note:
It should be noted that this protocol can over-request. The request is built, based on the quota at time t1 (_ReplicaManager.readFromLocalLog_). The bytes in the response are recorded at time t2 (end of _KafkaApis.handleFetchRequest_), where t2 > t1. For this reason I originally included an OverRequestedRate as a JMX metric, but testing has not seen revealed any obvious issue. Over-requesting is quickly compensated by subsequent requests, stabilising close to the quota value.

_**Main stuff left to do:**_
- The fetch size is currently unbounded. This will be addressed in KIP-74, but we need to ensure this ensures requests don\u2019t go beyond the throttle window.
- There are two failures showing up in the system tests on this branch:  StreamsSmokeTest.test_streams (which looks like it fails regularly) and OffsetValidationTest.test_broker_rolling_bounce (which I need to look into)

_**Stuff left to do that could be deferred:**_
- Add the extra metrics specified in the KIP.
- There are no system tests.
- There is no validation for the cluster size / throttle combination that could lead to ISR dropouts

Author: Ben Stopford <be...@gmail.com>

Reviewers: Ismael Juma <is...@juma.me.uk>, Apurva Mehta <ap...@confluent.io>, Jun Rao <ju...@gmail.com>

Closes #1776 from benstopford/rep-quotas-v2


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

Branch: refs/heads/trunk
Commit: 143a33bc506c703ea02fe5daa61f90b7094da13c
Parents: d436661
Author: Ben Stopford <be...@gmail.com>
Authored: Thu Sep 15 22:25:56 2016 -0700
Committer: Jun Rao <ju...@gmail.com>
Committed: Thu Sep 15 22:25:56 2016 -0700

----------------------------------------------------------------------
 .../common/metrics/QuotaViolationException.java |  27 ++-
 .../org/apache/kafka/common/metrics/Sensor.java |  12 +-
 .../apache/kafka/common/metrics/stats/Rate.java |   4 +-
 .../kafka/common/metrics/stats/SimpleRate.java  |  39 +++
 .../kafka/common/metrics/MetricsTest.java       |  59 +++++
 .../src/main/scala/kafka/admin/AdminUtils.scala |  26 +-
 .../main/scala/kafka/admin/ConfigCommand.scala  |  67 ++---
 .../kafka/admin/ReassignPartitionsCommand.scala | 142 +++++++++--
 .../kafka/consumer/ConsumerFetcherThread.scala  |   4 +-
 core/src/main/scala/kafka/log/LogConfig.scala   |  16 +-
 .../kafka/server/AbstractFetcherThread.scala    |   1 -
 .../scala/kafka/server/ClientQuotaManager.scala | 101 +++-----
 .../main/scala/kafka/server/ConfigHandler.scala |  98 ++++++--
 .../main/scala/kafka/server/DelayedFetch.scala  |  18 +-
 .../kafka/server/DynamicConfigManager.scala     |   6 +-
 .../src/main/scala/kafka/server/KafkaApis.scala |  62 ++---
 .../main/scala/kafka/server/KafkaConfig.scala   |  25 +-
 .../main/scala/kafka/server/KafkaServer.scala   |  14 +-
 .../main/scala/kafka/server/QuotaFactory.scala  |  74 ++++++
 .../kafka/server/ReplicaFetcherManager.scala    |  10 +-
 .../kafka/server/ReplicaFetcherThread.scala     |  22 +-
 .../scala/kafka/server/ReplicaManager.scala     |  27 ++-
 .../kafka/server/ReplicationQuotaManager.scala  | 202 ++++++++++++++++
 .../main/scala/kafka/server/SensorAccess.scala  |  76 ++++++
 core/src/main/scala/kafka/utils/CoreUtils.scala |   1 +
 core/src/main/scala/kafka/utils/Time.scala      |   2 +-
 .../kafka/api/ClientQuotasTest.scala            | 206 ++++++++++++++++
 .../integration/kafka/api/QuotasTest.scala      | 207 ----------------
 .../test/scala/unit/kafka/admin/AdminTest.scala | 102 ++++++--
 .../unit/kafka/admin/ConfigCommandTest.scala    | 188 ++++++++++++--
 .../admin/ReassignPartitionsClusterTest.scala   | 152 +++++++++++-
 .../admin/ReassignPartitionsCommandTest.scala   |  88 +++++++
 .../kafka/admin/ReplicationQuotaUtils.scala     |  51 ++++
 .../scala/unit/kafka/admin/TestAdminUtils.scala |  27 +++
 .../unit/kafka/integration/FetcherTest.scala    |   1 -
 .../scala/unit/kafka/log/LogConfigTest.scala    |  31 ++-
 .../server/AbstractFetcherThreadTest.scala      |   1 +
 .../kafka/server/ClientQuotaManagerTest.scala   |  22 +-
 .../kafka/server/DynamicConfigChangeTest.scala  | 103 +++++---
 .../server/HighwatermarkPersistenceTest.scala   |   9 +-
 .../unit/kafka/server/ISRExpirationTest.scala   |   2 +-
 .../kafka/server/ReplicaManagerQuotasTest.scala | 154 ++++++++++++
 .../unit/kafka/server/ReplicaManagerTest.scala  |  10 +-
 .../server/ReplicationQuotaManagerTest.scala    | 123 ++++++++++
 .../kafka/server/ReplicationQuotasTest.scala    | 242 +++++++++++++++++++
 .../unit/kafka/server/SimpleFetchTest.scala     |  24 +-
 .../ThrottledResponseExpirationTest.scala       |   2 +-
 .../test/scala/unit/kafka/utils/TestUtils.scala |  14 +-
 48 files changed, 2324 insertions(+), 570 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/clients/src/main/java/org/apache/kafka/common/metrics/QuotaViolationException.java
----------------------------------------------------------------------
diff --git a/clients/src/main/java/org/apache/kafka/common/metrics/QuotaViolationException.java b/clients/src/main/java/org/apache/kafka/common/metrics/QuotaViolationException.java
index fbe03f5..7e1a2c6 100644
--- a/clients/src/main/java/org/apache/kafka/common/metrics/QuotaViolationException.java
+++ b/clients/src/main/java/org/apache/kafka/common/metrics/QuotaViolationException.java
@@ -17,6 +17,7 @@
 package org.apache.kafka.common.metrics;
 
 import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.MetricName;
 
 /**
  * Thrown when a sensor records a value that causes a metric to go outside the bounds configured as its quota
@@ -24,8 +25,30 @@ import org.apache.kafka.common.KafkaException;
 public class QuotaViolationException extends KafkaException {
 
     private static final long serialVersionUID = 1L;
+    private final MetricName metricName;
+    private final double value;
+    private final double bound;
 
-    public QuotaViolationException(String m) {
-        super(m);
+    public QuotaViolationException(MetricName metricName, double value, double bound) {
+        super(String.format(
+                "'%s' violated quota. Actual: %f, Threshold: %f",
+                metricName,
+                value,
+                bound));
+        this.metricName = metricName;
+        this.value = value;
+        this.bound = bound;
+    }
+
+    public MetricName metricName() {
+        return metricName;
+    }
+
+    public double value() {
+        return value;
+    }
+
+    public double bound() {
+        return bound;
     }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java
----------------------------------------------------------------------
diff --git a/clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java b/clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java
index 3e500d5..4f630f9 100644
--- a/clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java
+++ b/clients/src/main/java/org/apache/kafka/common/metrics/Sensor.java
@@ -109,9 +109,12 @@ public final class Sensor {
 
     /**
      * Check if we have violated our quota for any metric that has a configured quota
-     * @param timeMs
      */
-    private void checkQuotas(long timeMs) {
+    public void checkQuotas() {
+        checkQuotas(time.milliseconds());
+    }
+
+    public void checkQuotas(long timeMs) {
         for (int i = 0; i < this.metrics.size(); i++) {
             KafkaMetric metric = this.metrics.get(i);
             MetricConfig config = metric.config();
@@ -120,11 +123,10 @@ public final class Sensor {
                 if (quota != null) {
                     double value = metric.value(timeMs);
                     if (!quota.acceptable(value)) {
-                        throw new QuotaViolationException(String.format(
-                            "'%s' violated quota. Actual: %f, Threshold: %f",
+                        throw new QuotaViolationException(
                             metric.metricName(),
                             value,
-                            quota.bound()));
+                            quota.bound());
                     }
                 }
             }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/clients/src/main/java/org/apache/kafka/common/metrics/stats/Rate.java
----------------------------------------------------------------------
diff --git a/clients/src/main/java/org/apache/kafka/common/metrics/stats/Rate.java b/clients/src/main/java/org/apache/kafka/common/metrics/stats/Rate.java
index 971b7b6..6e49649 100644
--- a/clients/src/main/java/org/apache/kafka/common/metrics/stats/Rate.java
+++ b/clients/src/main/java/org/apache/kafka/common/metrics/stats/Rate.java
@@ -28,8 +28,8 @@ import org.apache.kafka.common.metrics.MetricConfig;
  */
 public class Rate implements MeasurableStat {
 
-    private final TimeUnit unit;
-    private final SampledStat stat;
+    protected final TimeUnit unit;
+    protected final SampledStat stat;
 
     public Rate() {
         this(TimeUnit.SECONDS);

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/clients/src/main/java/org/apache/kafka/common/metrics/stats/SimpleRate.java
----------------------------------------------------------------------
diff --git a/clients/src/main/java/org/apache/kafka/common/metrics/stats/SimpleRate.java b/clients/src/main/java/org/apache/kafka/common/metrics/stats/SimpleRate.java
new file mode 100644
index 0000000..018f084
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/metrics/stats/SimpleRate.java
@@ -0,0 +1,39 @@
+/**
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ */
+package org.apache.kafka.common.metrics.stats;
+
+import org.apache.kafka.common.metrics.MetricConfig;
+
+/**
+ * A simple rate the rate is incrementally calculated
+ * based on the elapsed time between the earliest reading
+ * and now.
+ *
+ * An exception is made for the first window, which is
+ * considered of fixed size. This avoids the issue of
+ * an artificially high rate when the gap between readings
+ * is close to 0.
+ */
+public class SimpleRate extends Rate {
+
+    @Override
+    public long windowSize(MetricConfig config, long now) {
+        stat.purgeObsoleteSamples(config, now);
+        long elapsed = now - stat.oldest(now).lastWindowMs;
+        return elapsed < config.timeWindowMs() ? config.timeWindowMs() : elapsed;
+    }
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java
----------------------------------------------------------------------
diff --git a/clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java b/clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java
index 52f0cd7..5797b36 100644
--- a/clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/metrics/MetricsTest.java
@@ -35,6 +35,7 @@ import org.apache.kafka.common.metrics.stats.Percentiles;
 import org.apache.kafka.common.metrics.stats.Percentiles.BucketSizing;
 import org.apache.kafka.common.metrics.stats.Rate;
 import org.apache.kafka.common.metrics.stats.Total;
+import org.apache.kafka.common.metrics.stats.SimpleRate;
 import org.apache.kafka.common.utils.MockTime;
 import org.junit.After;
 import org.junit.Before;
@@ -459,4 +460,62 @@ public class MetricsTest {
 
     }
 
+    @Test
+    public void testSimpleRate() {
+        SimpleRate rate = new SimpleRate();
+
+        //Given
+        MetricConfig config = new MetricConfig().timeWindow(1, TimeUnit.SECONDS).samples(10);
+
+        //In the first window the rate is a fraction of the whole (1s) window
+        //So when we record 1000 at t0, the rate should be 1000 until the window completes, or more data is recorded.
+        record(rate, config, 1000);
+        assertEquals(1000, measure(rate, config), 0);
+        time.sleep(100);
+        assertEquals(1000, measure(rate, config), 0); // 1000B / 0.1s
+        time.sleep(100);
+        assertEquals(1000, measure(rate, config), 0); // 1000B / 0.2s
+        time.sleep(200);
+        assertEquals(1000, measure(rate, config), 0); // 1000B / 0.4s
+
+        //In the second (and subsequent) window(s), the rate will be in proportion to the elapsed time
+        //So the rate will degrade over time, as the time between measurement and the initial recording grows.
+        time.sleep(600);
+        assertEquals(1000, measure(rate, config), 0); // 1000B / 1.0s
+        time.sleep(200);
+        assertEquals(1000 / 1.2, measure(rate, config), 0); // 1000B / 1.2s
+        time.sleep(200);
+        assertEquals(1000 / 1.4, measure(rate, config), 0); // 1000B / 1.4s
+
+        //Adding another value, inside the same window should double the rate
+        record(rate, config, 1000);
+        assertEquals(2000 / 1.4, measure(rate, config), 0); // 2000B / 1.4s
+
+        //Going over the next window, should not change behaviour
+        time.sleep(1100);
+        assertEquals(2000 / 2.5, measure(rate, config), 0); // 2000B / 2.5s
+        record(rate, config, 1000);
+        assertEquals(3000 / 2.5, measure(rate, config), 0); // 3000B / 2.5s
+
+        //Sleeping for another 6.5 windows also should be the same
+        time.sleep(6500);
+        assertEquals(3000 / 9, measure(rate, config), 1); // 3000B / 9s
+        record(rate, config, 1000);
+        assertEquals(4000 / 9, measure(rate, config), 1); // 4000B / 9s
+
+        //Going over the 10 window boundary should cause the first window's values (1000) will be purged.
+        //So the rate is calculated based on the oldest reading, which is inside the second window, at 1.4s
+        time.sleep(1500);
+        assertEquals((4000 - 1000) / (10.5 - 1.4), measure(rate, config), 1);
+        record(rate, config, 1000);
+        assertEquals((5000 - 1000) / (10.5 - 1.4), measure(rate, config), 1);
+    }
+
+    private void record(Rate rate, MetricConfig config, int value) {
+        rate.record(config, value, time.milliseconds());
+    }
+
+    private Double measure(Measurable rate, MetricConfig config) {
+        return rate.measure(config, time.milliseconds());
+    }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/admin/AdminUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/admin/AdminUtils.scala b/core/src/main/scala/kafka/admin/AdminUtils.scala
index d8702df..400cc47 100644
--- a/core/src/main/scala/kafka/admin/AdminUtils.scala
+++ b/core/src/main/scala/kafka/admin/AdminUtils.scala
@@ -20,7 +20,7 @@ package kafka.admin
 import kafka.common._
 import kafka.cluster.Broker
 import kafka.log.LogConfig
-import kafka.server.ConfigType
+import kafka.server.{KafkaConfig, ConfigType}
 import kafka.utils._
 import kafka.utils.ZkUtils._
 import java.util.Random
@@ -38,7 +38,14 @@ import collection.Map
 import collection.Set
 import org.I0Itec.zkclient.exception.ZkNodeExistsException
 
-object AdminUtils extends Logging {
+trait AdminUtilities {
+  def changeTopicConfig(zkUtils: ZkUtils, topic: String, configs: Properties)
+  def changeClientIdConfig(zkUtils: ZkUtils, clientId: String, configs: Properties)
+  def changeBrokerConfig(zkUtils: ZkUtils, brokerIds: Seq[Int], configs: Properties)
+  def fetchEntityConfig(zkUtils: ZkUtils,entityType: String, entityName: String): Properties
+}
+
+object AdminUtils extends Logging with AdminUtilities {
   val rand = new Random
   val AdminClientId = "__admin_client"
   val EntityConfigChangeZnodePrefix = "config_change_"
@@ -498,6 +505,21 @@ object AdminUtils extends Logging {
     changeEntityConfig(zkUtils, ConfigType.Topic, topic, configs)
   }
 
+  /**
+    * Override the broker config on some set of brokers. These overrides will be persisted between sessions, and will
+    * override any defaults entered in the broker's config files
+    *
+    * @param zkUtils: Zookeeper utilities used to write the config to ZK
+    * @param brokers: The list of brokers to apply config changes to
+    * @param configs: The config to change, as properties
+    */
+  def changeBrokerConfig(zkUtils: ZkUtils, brokers: Seq[Int], configs: Properties): Unit = {
+    KafkaConfig.validateNames(configs)
+    brokers.foreach { broker =>
+      changeEntityConfig(zkUtils, ConfigType.Broker, broker.toString, configs)
+    }
+  }
+
   private def changeEntityConfig(zkUtils: ZkUtils, entityType: String, entityName: String, configs: Properties) {
     // write the new config--may not exist if there were previously no overrides
     writeEntityConfig(zkUtils, entityType, entityName, configs)

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/admin/ConfigCommand.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/admin/ConfigCommand.scala b/core/src/main/scala/kafka/admin/ConfigCommand.scala
index eaddd84..ebf9e61 100644
--- a/core/src/main/scala/kafka/admin/ConfigCommand.scala
+++ b/core/src/main/scala/kafka/admin/ConfigCommand.scala
@@ -22,7 +22,7 @@ import java.util.Properties
 import joptsimple._
 import kafka.admin.TopicCommand._
 import kafka.log.{Defaults, LogConfig}
-import kafka.server.{ClientConfigOverride, ConfigType}
+import kafka.server.{KafkaConfig, ClientConfigOverride, ConfigType}
 import kafka.utils.{CommandLineUtils, ZkUtils}
 import org.apache.kafka.common.security.JaasUtils
 import org.apache.kafka.common.utils.Utils
@@ -32,7 +32,7 @@ import scala.collection._
 
 
 /**
- * This script can be used to change configs for topics/clients dynamically
+ * This script can be used to change configs for topics/clients/brokers dynamically
  */
 object ConfigCommand {
 
@@ -41,7 +41,7 @@ object ConfigCommand {
     val opts = new ConfigCommandOptions(args)
 
     if(args.length == 0)
-      CommandLineUtils.printUsageAndDie(opts.parser, "Add/Remove entity (topics/clients) configs")
+      CommandLineUtils.printUsageAndDie(opts.parser, "Add/Remove entity config for a topic, client or broker")
 
     opts.checkArgs()
 
@@ -64,7 +64,7 @@ object ConfigCommand {
     }
   }
 
-  private def alterConfig(zkUtils: ZkUtils, opts: ConfigCommandOptions) {
+  def alterConfig(zkUtils: ZkUtils, opts: ConfigCommandOptions, utils: AdminUtilities = AdminUtils) {
     val configsToBeAdded = parseConfigsToBeAdded(opts)
     val configsToBeDeleted = parseConfigsToBeDeleted(opts)
     val entityType = opts.options.valueOf(opts.entityType)
@@ -72,17 +72,17 @@ object ConfigCommand {
     warnOnMaxMessagesChange(configsToBeAdded, opts.options.has(opts.forceOpt))
 
     // compile the final set of configs
-    val configs = AdminUtils.fetchEntityConfig(zkUtils, entityType, entityName)
+    val configs = utils.fetchEntityConfig(zkUtils, entityType, entityName)
     configs.putAll(configsToBeAdded)
     configsToBeDeleted.foreach(config => configs.remove(config))
 
-    if (entityType.equals(ConfigType.Topic)) {
-      AdminUtils.changeTopicConfig(zkUtils, entityName, configs)
-      println("Updated config for topic: \"%s\".".format(entityName))
-    } else {
-      AdminUtils.changeClientIdConfig(zkUtils, entityName, configs)
-      println("Updated config for clientId: \"%s\".".format(entityName))
+    entityType match {
+      case ConfigType.Topic =>  utils.changeTopicConfig(zkUtils, entityName, configs)
+      case ConfigType.Client =>  utils.changeClientIdConfig(zkUtils, entityName, configs)
+      case ConfigType.Broker => utils.changeBrokerConfig(zkUtils, Seq(parseBroker(entityName)), configs)
+      case _ => throw new IllegalArgumentException(s"$entityType is not a known entityType. Should be one of ${ConfigType.Topic}, ${ConfigType.Client}, ${ConfigType.Broker}")
     }
+    println(s"Updated config for EntityType:$entityType => EntityName:'$entityName'.")
   }
 
   def warnOnMaxMessagesChange(configs: Properties, force: Boolean): Unit = {
@@ -97,6 +97,15 @@ object ConfigCommand {
     }
   }
 
+  private def parseBroker(broker: String): Int = {
+    try {
+      broker.toInt
+    }catch {
+      case e: NumberFormatException =>
+        throw new IllegalArgumentException(s"Error parsing broker $broker. The broker's Entity Name must be a single integer value")
+    }
+  }
+
   private def describeConfig(zkUtils: ZkUtils, opts: ConfigCommandOptions) {
     val entityType = opts.options.valueOf(opts.entityType)
     val entityNames: Seq[String] =
@@ -113,14 +122,19 @@ object ConfigCommand {
   }
 
   private[admin] def parseConfigsToBeAdded(opts: ConfigCommandOptions): Properties = {
-    val configsToBeAdded = opts.options.valuesOf(opts.addConfig).map(_.split("""\s*=\s*"""))
-    require(configsToBeAdded.forall(config => config.length == 2),
-      "Invalid entity config: all configs to be added must be in the format \"key=val\".")
     val props = new Properties
-    configsToBeAdded.foreach(pair => props.setProperty(pair(0).trim, pair(1).trim))
-    if (props.containsKey(LogConfig.MessageFormatVersionProp)) {
-      println(s"WARNING: The configuration ${LogConfig.MessageFormatVersionProp}=${props.getProperty(LogConfig.MessageFormatVersionProp)} is specified. " +
-        s"This configuration will be ignored if the version is newer than the inter.broker.protocol.version specified in the broker.")
+    if (opts.options.has(opts.addConfig)) {
+      //split by commas, but avoid those in [], then into KV pairs
+      val configsToBeAdded = opts.options.valueOf(opts.addConfig)
+        .split(",(?=[^\\]]*(?:\\[|$))")
+        .map(_.split("""\s*=\s*"""))
+      require(configsToBeAdded.forall(config => config.length == 2), "Invalid entity config: all configs to be added must be in the format \"key=val\".")
+      //Create properties, parsing square brackets from values if necessary
+      configsToBeAdded.foreach(pair => props.setProperty(pair(0).trim, pair(1).replaceAll("\\[?\\]?", "").trim))
+      if (props.containsKey(LogConfig.MessageFormatVersionProp)) {
+        println(s"WARNING: The configuration ${LogConfig.MessageFormatVersionProp}=${props.getProperty(LogConfig.MessageFormatVersionProp)} is specified. " +
+          s"This configuration will be ignored if the version is newer than the inter.broker.protocol.version specified in the broker.")
+      }
     }
     props
   }
@@ -145,21 +159,21 @@ object ConfigCommand {
             .ofType(classOf[String])
     val alterOpt = parser.accepts("alter", "Alter the configuration for the entity.")
     val describeOpt = parser.accepts("describe", "List configs for the given entity.")
-    val entityType = parser.accepts("entity-type", "Type of entity (topics/clients)")
+    val entityType = parser.accepts("entity-type", "Type of entity (topics/clients/brokers)")
             .withRequiredArg
             .ofType(classOf[String])
-    val entityName = parser.accepts("entity-name", "Name of entity (topic name/client id)")
+    val entityName = parser.accepts("entity-name", "Name of entity (topic name/client id/broker id)")
             .withRequiredArg
             .ofType(classOf[String])
 
     val nl = System.getProperty("line.separator")
-    val addConfig = parser.accepts("add-config", "Key Value pairs configs to add 'k1=v1,k2=v2'. The following is a list of valid configurations: " +
+    val addConfig = parser.accepts("add-config", "Key Value pairs of configs to add. Square brackets can be used to group values which contain commas: 'k1=v1,k2=[v1,v2,v2],k3=v3'. The following is a list of valid configurations: " +
             "For entity_type '" + ConfigType.Topic + "': " + nl + LogConfig.configNames.map("\t" + _).mkString(nl) + nl +
+            "For entity_type '" + ConfigType.Broker + "': " + nl + KafkaConfig.dynamicBrokerConfigs.map("\t" + _).mkString(nl) + nl +
             "For entity_type '" + ConfigType.Client + "': " + nl + "\t" + ClientConfigOverride.ProducerOverride
                                                             + nl + "\t" + ClientConfigOverride.ConsumerOverride)
             .withRequiredArg
             .ofType(classOf[String])
-            .withValuesSeparatedBy(',')
     val deleteConfig = parser.accepts("delete-config", "config keys to remove 'k1,k2'")
             .withRequiredArg
             .ofType(classOf[String])
@@ -181,19 +195,14 @@ object ConfigCommand {
       CommandLineUtils.checkInvalidArgs(parser, options, alterOpt, Set(describeOpt))
       CommandLineUtils.checkInvalidArgs(parser, options, describeOpt, Set(alterOpt, addConfig, deleteConfig))
       if(options.has(alterOpt)) {
-        if(! options.has(entityName))
-          throw new IllegalArgumentException("--entity-name must be specified with --alter")
+        require(options.has(entityName), "--entity-name must be specified with --alter")
 
         val isAddConfigPresent: Boolean = options.has(addConfig)
         val isDeleteConfigPresent: Boolean = options.has(deleteConfig)
         if(! isAddConfigPresent && ! isDeleteConfigPresent)
           throw new IllegalArgumentException("At least one of --add-config or --delete-config must be specified with --alter")
       }
-      val entityTypeVal = options.valueOf(entityType)
-      if(! entityTypeVal.equals(ConfigType.Topic) && ! entityTypeVal.equals(ConfigType.Client)) {
-        throw new IllegalArgumentException("--entity-type must be '%s' or '%s'".format(ConfigType.Topic, ConfigType.Client))
-      }
+      require(ConfigType.all.contains(options.valueOf(entityType)), s"--entity-type must be one of ${ConfigType.all}")
     }
   }
-
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/admin/ReassignPartitionsCommand.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/admin/ReassignPartitionsCommand.scala b/core/src/main/scala/kafka/admin/ReassignPartitionsCommand.scala
index 0b32d93..ad050b4 100755
--- a/core/src/main/scala/kafka/admin/ReassignPartitionsCommand.scala
+++ b/core/src/main/scala/kafka/admin/ReassignPartitionsCommand.scala
@@ -16,10 +16,13 @@
  */
 package kafka.admin
 
+import java.text.NumberFormat._
+import java.util.Properties
 import joptsimple.OptionParser
+import kafka.log.LogConfig
+import kafka.server.{ConfigType, KafkaConfig}
 import kafka.utils._
-import collection._
-import org.I0Itec.zkclient.ZkClient
+import scala.collection._
 import org.I0Itec.zkclient.exception.ZkNodeExistsException
 import kafka.common.{TopicAndPartition, AdminCommandFailedException}
 import org.apache.kafka.common.utils.Utils
@@ -27,6 +30,8 @@ import org.apache.kafka.common.security.JaasUtils
 
 object ReassignPartitionsCommand extends Logging {
 
+  //TODO Note to reviewer - this class needs a little more work (which I'll complete on Monday, or we could just revert this, but including here as an outline of what is intended)
+
   def main(args: Array[String]): Unit = {
 
     val opts = new ReassignPartitionsCommandOptions(args)
@@ -62,9 +67,12 @@ object ReassignPartitionsCommand extends Logging {
       CommandLineUtils.printUsageAndDie(opts.parser, "If --verify option is used, command must include --reassignment-json-file that was used during the --execute option")
     val jsonFile = opts.options.valueOf(opts.reassignmentJsonFileOpt)
     val jsonString = Utils.readFileAsString(jsonFile)
-    val partitionsToBeReassigned = ZkUtils.parsePartitionReassignmentData(jsonString)
+    verifyAssignment(zkUtils, jsonString)
+  }
 
+  def verifyAssignment(zkUtils: ZkUtils, jsonString: String): Unit = {
     println("Status of partition reassignment:")
+    val partitionsToBeReassigned = ZkUtils.parsePartitionReassignmentData(jsonString)
     val reassignedPartitionsStatus = checkIfReassignmentSucceeded(zkUtils, partitionsToBeReassigned)
     reassignedPartitionsStatus.foreach { case (topicPartition, status) =>
       status match {
@@ -76,6 +84,28 @@ object ReassignPartitionsCommand extends Logging {
           println("Reassignment of partition %s is still in progress".format(topicPartition))
       }
     }
+    removeThrottle(zkUtils, partitionsToBeReassigned, reassignedPartitionsStatus)
+  }
+
+  def removeThrottle(zkUtils: ZkUtils, partitionsToBeReassigned: Map[TopicAndPartition, scala.Seq[Int]], reassignedPartitionsStatus: Map[TopicAndPartition, ReassignmentStatus]): Unit = {
+    //If all partitions have completed remove the throttle
+    if (reassignedPartitionsStatus.forall { case (topicPartition, status) => status == ReassignmentCompleted }) {
+      //Remove the throttle limit from all brokers in the cluster
+      for (brokerId <- zkUtils.getAllBrokersInCluster().map(_.id)) {
+        val configs = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Broker, brokerId.toString)
+        if (configs.remove(KafkaConfig.ThrottledReplicationRateLimitProp) != null)
+          AdminUtils.changeBrokerConfig(zkUtils, Seq(brokerId), configs)
+      }
+
+      //Remove the list of throttled replicas from all topics with partitions being moved
+      val topics = partitionsToBeReassigned.keySet.map(tp => tp.topic).toSeq.distinct
+      for (topic <- topics) {
+        val configs = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Topic, topic)
+        if (configs.remove(LogConfig.ThrottledReplicasListProp) != null)
+          AdminUtils.changeTopicConfig(zkUtils, topic, configs)
+      }
+      println("Throttle was removed.")
+    }
   }
 
   def generateAssignment(zkUtils: ZkUtils, opts: ReassignPartitionsCommandOptions) {
@@ -112,7 +142,6 @@ object ReassignPartitionsCommand extends Logging {
         TopicAndPartition(topic, partition) -> replicas
       }
     }
-
     (partitionsToBeReassigned, currentAssignment)
   }
 
@@ -121,11 +150,38 @@ object ReassignPartitionsCommand extends Logging {
       CommandLineUtils.printUsageAndDie(opts.parser, "If --execute option is used, command must include --reassignment-json-file that was output " + "during the --generate option")
     val reassignmentJsonFile =  opts.options.valueOf(opts.reassignmentJsonFileOpt)
     val reassignmentJsonString = Utils.readFileAsString(reassignmentJsonFile)
-    executeAssignment(zkUtils, reassignmentJsonString)
+    val throttle = if (opts.options.has(opts.throttleOpt)) opts.options.valueOf(opts.throttleOpt) else -1
+    executeAssignment(zkUtils, reassignmentJsonString, throttle)
   }
 
-  def executeAssignment(zkUtils: ZkUtils, reassignmentJsonString: String) {
+  def executeAssignment(zkUtils: ZkUtils, reassignmentJsonString: String, throttle: Long = -1) {
+    val partitionsToBeReassigned = parseAndValidate(reassignmentJsonString)
+    val reassignPartitionsCommand = new ReassignPartitionsCommand(zkUtils, partitionsToBeReassigned.toMap)
+
+    // If there is an existing rebalance running, attempt to change its throttle
+    if (zkUtils.pathExists(ZkUtils.ReassignPartitionsPath)) {
+      println("There is an existing assignment running.")
+      reassignPartitionsCommand.maybeLimit(throttle)
+    }
+    else {
+      printCurrentAssignment(zkUtils, partitionsToBeReassigned)
+      if (throttle >= 0)
+        println(String.format("Warning: You must run Verify periodically, until the reassignment completes, to ensure the throttle is removed. You can also alter the throttle by rerunning the Execute command passing a new value."))
+      if (reassignPartitionsCommand.reassignPartitions(throttle)) {
+        println("Successfully started reassignment of partitions.")
+      } else
+        println("Failed to reassign partitions %s".format(partitionsToBeReassigned))
+    }
+  }
+
+  def printCurrentAssignment(zkUtils: ZkUtils, partitionsToBeReassigned: scala.Seq[(TopicAndPartition, scala.Seq[Int])]): Unit = {
+    // before starting assignment, output the current replica assignment to facilitate rollback
+    val currentPartitionReplicaAssignment = zkUtils.getReplicaAssignmentForTopics(partitionsToBeReassigned.map(_._1.topic))
+    println("Current partition replica assignment\n\n%s\n\nSave this to use as the --reassignment-json-file option during rollback"
+      .format(ZkUtils.formatAsReassignmentJson(currentPartitionReplicaAssignment)))
+  }
 
+  def parseAndValidate(reassignmentJsonString: String): scala.Seq[(TopicAndPartition, scala.Seq[Int])] = {
     val partitionsToBeReassigned = ZkUtils.parsePartitionReassignmentDataWithoutDedup(reassignmentJsonString)
     if (partitionsToBeReassigned.isEmpty)
       throw new AdminCommandFailedException("Partition reassignment data file is empty")
@@ -141,16 +197,7 @@ object ReassignPartitionsCommand extends Logging {
         .mkString(". ")
       throw new AdminCommandFailedException("Partition replica lists may not contain duplicate entries: %s".format(duplicatesMsg))
     }
-    val reassignPartitionsCommand = new ReassignPartitionsCommand(zkUtils, partitionsToBeReassigned.toMap)
-    // before starting assignment, output the current replica assignment to facilitate rollback
-    val currentPartitionReplicaAssignment = zkUtils.getReplicaAssignmentForTopics(partitionsToBeReassigned.map(_._1.topic))
-    println("Current partition replica assignment\n\n%s\n\nSave this to use as the --reassignment-json-file option during rollback"
-      .format(ZkUtils.formatAsReassignmentJson(currentPartitionReplicaAssignment)))
-    // start the reassignment
-    if (reassignPartitionsCommand.reassignPartitions())
-      println("Successfully started reassignment of partitions %s".format(ZkUtils.formatAsReassignmentJson(partitionsToBeReassigned.toMap)))
-    else
-      println("Failed to reassign partitions %s".format(partitionsToBeReassigned))
+    partitionsToBeReassigned
   }
 
   private def checkIfReassignmentSucceeded(zkUtils: ZkUtils, partitionsToBeReassigned: Map[TopicAndPartition, Seq[Int]])
@@ -192,7 +239,7 @@ object ReassignPartitionsCommand extends Logging {
     val generateOpt = parser.accepts("generate", "Generate a candidate partition reassignment configuration." +
       " Note that this only generates a candidate assignment, it does not execute it.")
     val executeOpt = parser.accepts("execute", "Kick off the reassignment as specified by the --reassignment-json-file option.")
-    val verifyOpt = parser.accepts("verify", "Verify if the reassignment completed as specified by the --reassignment-json-file option.")
+    val verifyOpt = parser.accepts("verify", "Verify if the reassignment completed as specified by the --reassignment-json-file option. If there is a throttle engaged for the replicas specified, and the rebalance has completed, the throttle will be removed")
     val reassignmentJsonFileOpt = parser.accepts("reassignment-json-file", "The JSON file with the partition reassignment configuration" +
                       "The format to use is - \n" +
                       "{\"partitions\":\n\t[{\"topic\": \"foo\",\n\t  \"partition\": 1,\n\t  \"replicas\": [1,2,3] }],\n\"version\":1\n}")
@@ -211,7 +258,11 @@ object ReassignPartitionsCommand extends Logging {
                       .describedAs("brokerlist")
                       .ofType(classOf[String])
     val disableRackAware = parser.accepts("disable-rack-aware", "Disable rack aware replica assignment")
-
+    val throttleOpt = parser.accepts("throttle", "The movement of partitions will be throttled to this value (bytes/sec). Rerunning with this option, whilst a rebalance is in progress, will alter the throttle value.")
+                      .withRequiredArg()
+                      .describedAs("throttle")
+                      .defaultsTo("-1")
+                      .ofType(classOf[Long])
     if(args.length == 0)
       CommandLineUtils.printUsageAndDie(parser, "This command moves topic partitions between replicas.")
 
@@ -219,9 +270,60 @@ object ReassignPartitionsCommand extends Logging {
   }
 }
 
-class ReassignPartitionsCommand(zkUtils: ZkUtils, partitions: collection.Map[TopicAndPartition, collection.Seq[Int]])
+class ReassignPartitionsCommand(zkUtils: ZkUtils, partitions: Map[TopicAndPartition, Seq[Int]])
   extends Logging {
-  def reassignPartitions(): Boolean = {
+
+  private def maybeThrottle(throttle: Long): Unit = {
+    if (throttle >= 0) {
+      maybeLimit(throttle)
+      addThrottledReplicaList()
+    }
+  }
+
+  def maybeLimit(throttle: Long) {
+    if (throttle >= 0) {
+      val existingBrokers = zkUtils.getReplicaAssignmentForTopics(partitions.map(_._1.topic).toSeq).flatMap(_._2).toSeq
+      val proposedBrokers = partitions.flatMap(_._2).toSeq
+      val brokers = (existingBrokers ++ proposedBrokers).distinct
+
+      for (id <- brokers) {
+        val configs = AdminUtils.fetchEntityConfig(zkUtils, ConfigType.Broker, id.toString)
+        configs.put(KafkaConfig.ThrottledReplicationRateLimitProp, throttle.toString)
+        AdminUtils.changeBrokerConfig(zkUtils, Seq(id), configs)
+      }
+      println(f"The throttle limit was set to $throttle%,d B/s")
+    }
+  }
+
+  def addThrottledReplicaList(): Unit = {
+    //apply the throttle to all move destinations and all move sources
+    val existing = zkUtils.getReplicaAssignmentForTopics(partitions.map(_._1.topic).toSeq)
+    val moves = replicaMoves(existing, proposed = partitions)
+    for (topic <- partitions.keySet.map(tp => tp.topic).toSeq.distinct)
+      AdminUtils.changeTopicConfig(zkUtils, topic, new Properties {
+        put(LogConfig.ThrottledReplicasListProp, moves.get(topic).get )
+      })
+    println(s"Throttles were added to the following replicas: $moves")
+  }
+
+  def replicaMoves(existing: Map[TopicAndPartition, Seq[Int]], proposed: Map[TopicAndPartition, Seq[Int]]): Map[String, String] = {
+    //Find the replicas that have moved
+    val movesByPartition = existing.map { case (topicAndPartition, existingReplicas) =>
+      val before = existingReplicas.toSet
+      val after = proposed.get(topicAndPartition).get.toSet
+      val moving = (after.filterNot(before) ++ before.filterNot(after)).toSeq.distinct.sorted
+      val formatted = moving.map { brokerId => s"${topicAndPartition.partition}:$brokerId" }
+      (topicAndPartition, formatted)
+    }
+    //Group by topic
+    val movesByTopic = movesByPartition.groupBy(_._1.topic)
+      .map { case (topic, reps) => (topic, reps.values.flatMap(rep => rep)) }
+
+    movesByTopic.map { case (topic, moves) => topic -> moves.mkString(",") }
+  }
+
+  def reassignPartitions(throttle: Long = -1): Boolean = {
+    maybeThrottle(throttle)
     try {
       val validPartitions = partitions.filter(p => validatePartition(zkUtils, p._1.topic, p._1.partition))
       if (validPartitions.isEmpty) false

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/consumer/ConsumerFetcherThread.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/consumer/ConsumerFetcherThread.scala b/core/src/main/scala/kafka/consumer/ConsumerFetcherThread.scala
index 8801ff8..c33122b 100644
--- a/core/src/main/scala/kafka/consumer/ConsumerFetcherThread.scala
+++ b/core/src/main/scala/kafka/consumer/ConsumerFetcherThread.scala
@@ -22,8 +22,7 @@ import kafka.cluster.BrokerEndPoint
 import kafka.message.ByteBufferMessageSet
 import kafka.server.{PartitionFetchState, AbstractFetcherThread}
 import kafka.common.{ErrorMapping, TopicAndPartition}
-import scala.collection.JavaConverters
-import JavaConverters._
+import scala.collection.Map
 import ConsumerFetcherThread._
 
 class ConsumerFetcherThread(name: String,
@@ -108,7 +107,6 @@ class ConsumerFetcherThread(name: String,
     simpleConsumer.fetch(fetchRequest.underlying).data.map { case (key, value) =>
       key -> new PartitionData(value)
     }
-
 }
 
 object ConsumerFetcherThread {

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/log/LogConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/log/LogConfig.scala b/core/src/main/scala/kafka/log/LogConfig.scala
index b8efcc3..f01166d 100755
--- a/core/src/main/scala/kafka/log/LogConfig.scala
+++ b/core/src/main/scala/kafka/log/LogConfig.scala
@@ -22,7 +22,7 @@ import java.util.Properties
 import scala.collection.JavaConverters._
 import kafka.api.ApiVersion
 import kafka.message.{BrokerCompressionCodec, Message}
-import kafka.server.KafkaConfig
+import kafka.server.{ThrottledReplicaValidator, KafkaConfig}
 import org.apache.kafka.common.errors.InvalidConfigurationException
 import org.apache.kafka.common.config.{AbstractConfig, ConfigDef}
 import org.apache.kafka.common.record.TimestampType
@@ -30,7 +30,7 @@ import org.apache.kafka.common.utils.Utils
 import java.util.Locale
 
 import scala.collection.mutable
-import org.apache.kafka.common.config.ConfigDef.{ConfigKey, ValidList}
+import org.apache.kafka.common.config.ConfigDef.{ConfigKey, ValidList,Validator}
 
 object Defaults {
   val SegmentSize = kafka.server.Defaults.LogSegmentBytes
@@ -55,6 +55,7 @@ object Defaults {
   val MessageFormatVersion = kafka.server.Defaults.LogMessageFormatVersion
   val MessageTimestampType = kafka.server.Defaults.LogMessageTimestampType
   val MessageTimestampDifferenceMaxMs = kafka.server.Defaults.LogMessageTimestampDifferenceMaxMs
+  val ThrottledReplicasList = ""
 }
 
 case class LogConfig(props: java.util.Map[_, _]) extends AbstractConfig(LogConfig.configDef, props, false) {
@@ -85,6 +86,7 @@ case class LogConfig(props: java.util.Map[_, _]) extends AbstractConfig(LogConfi
   val messageFormatVersion = ApiVersion(getString(LogConfig.MessageFormatVersionProp))
   val messageTimestampType = TimestampType.forName(getString(LogConfig.MessageTimestampTypeProp))
   val messageTimestampDifferenceMaxMs = getLong(LogConfig.MessageTimestampDifferenceMaxMsProp).longValue
+  val throttledReplicasList = getString(LogConfig.ThrottledReplicasListProp)
 
   def randomSegmentJitter: Long =
     if (segmentJitterMs == 0) 0 else Utils.abs(scala.util.Random.nextInt()) % math.min(segmentJitterMs, segmentMs)
@@ -121,6 +123,7 @@ object LogConfig {
   val MessageFormatVersionProp = "message.format.version"
   val MessageTimestampTypeProp = "message.timestamp.type"
   val MessageTimestampDifferenceMaxMsProp = "message.timestamp.difference.max.ms"
+  val ThrottledReplicasListProp = "quota.replication.throttled.replicas"
 
   val SegmentSizeDoc = "This configuration controls the segment file size for " +
     "the log. Retention and cleaning is always done a file at a time so a larger " +
@@ -190,13 +193,15 @@ object LogConfig {
   val MessageTimestampTypeDoc = KafkaConfig.LogMessageTimestampTypeDoc
   val MessageTimestampDifferenceMaxMsDoc = "The maximum difference allowed between the timestamp when a broker receives " +
     "a message and the timestamp specified in the message. If message.timestamp.type=CreateTime, a message will be rejected " +
-    "if the difference in timestamp exceeds this threshold. This configuration is ignored if message.timestamp.type=LogAppendTime."  
+    "if the difference in timestamp exceeds this threshold. This configuration is ignored if message.timestamp.type=LogAppendTime."
+  val ThrottledReplicasListDoc = "A list of replicas for which log replication should be throttled. The list should describe a set of " +
+    "replicas in the form [PartitionId]:[BrokerId],[PartitionId]:[BrokerId]:..."
 
   private class LogConfigDef extends ConfigDef {
 
     private final val serverDefaultConfigNames = mutable.Map[String, String]()
 
-    def define(name: String, defType: ConfigDef.Type, defaultValue: Any, validator: ConfigDef.Validator,
+    def define(name: String, defType: ConfigDef.Type, defaultValue: Any, validator: Validator,
                importance: ConfigDef.Importance, doc: String, serverDefaultConfigName: String): LogConfigDef = {
       super.define(name, defType, defaultValue, validator, importance, doc)
       serverDefaultConfigNames.put(name, serverDefaultConfigName)
@@ -280,6 +285,7 @@ object LogConfig {
         KafkaConfig.LogMessageTimestampTypeProp)
       .define(MessageTimestampDifferenceMaxMsProp, LONG, Defaults.MessageTimestampDifferenceMaxMs,
         atLeast(0), MEDIUM, MessageTimestampDifferenceMaxMsDoc, KafkaConfig.LogMessageTimestampDifferenceMaxMsProp)
+      .define(ThrottledReplicasListProp, STRING, Defaults.ThrottledReplicasList, ThrottledReplicaValidator, MEDIUM, ThrottledReplicasListDoc, ThrottledReplicasListProp)
   }
 
   def apply(): LogConfig = LogConfig(new Properties())
@@ -303,7 +309,7 @@ object LogConfig {
     val names = configNames
     for(name <- props.asScala.keys)
       if (!names.contains(name))
-        throw new InvalidConfigurationException(s"Unknown configuration $name.")
+        throw new InvalidConfigurationException(s"Unknown Log configuration $name.")
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/AbstractFetcherThread.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/AbstractFetcherThread.scala b/core/src/main/scala/kafka/server/AbstractFetcherThread.scala
index 4aba667..36baf1f 100755
--- a/core/src/main/scala/kafka/server/AbstractFetcherThread.scala
+++ b/core/src/main/scala/kafka/server/AbstractFetcherThread.scala
@@ -93,7 +93,6 @@ abstract class AbstractFetcherThread(name: String,
       }
       fetchRequest
     }
-
     if (!fetchRequest.isEmpty)
       processFetchRequest(fetchRequest)
   }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ClientQuotaManager.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ClientQuotaManager.scala b/core/src/main/scala/kafka/server/ClientQuotaManager.scala
index 5e90080..e6cac5d 100644
--- a/core/src/main/scala/kafka/server/ClientQuotaManager.scala
+++ b/core/src/main/scala/kafka/server/ClientQuotaManager.scala
@@ -17,7 +17,6 @@
 package kafka.server
 
 import java.util.concurrent.{ConcurrentHashMap, DelayQueue, TimeUnit}
-
 import kafka.utils.{ShutdownableThread, Logging}
 import org.apache.kafka.common.MetricName
 import org.apache.kafka.common.metrics._
@@ -66,18 +65,19 @@ object ClientQuotaManagerConfig {
  */
 class ClientQuotaManager(private val config: ClientQuotaManagerConfig,
                          private val metrics: Metrics,
-                         private val apiKey: String,
+                         private val apiKey: QuotaType,
                          private val time: Time) extends Logging {
   private val overriddenQuota = new ConcurrentHashMap[String, Quota]()
   private val defaultQuota = Quota.upperBound(config.quotaBytesPerSecondDefault)
   private val lock = new ReentrantReadWriteLock()
   private val delayQueue = new DelayQueue[ThrottledResponse]()
+  private val sensorAccessor = new SensorAccess
   val throttledRequestReaper = new ThrottledRequestReaper(delayQueue)
   throttledRequestReaper.start()
 
   private val delayQueueSensor = metrics.sensor(apiKey + "-delayQueue")
   delayQueueSensor.add(metrics.metricName("queue-size",
-                                      apiKey,
+                                      apiKey.toString,
                                       "Tracks the size of the delay queue"), new Total())
 
   /**
@@ -164,71 +164,24 @@ class ClientQuotaManager(private val config: ClientQuotaManagerConfig,
    * First sensor of the tuple is the quota enforcement sensor. Second one is the throttle time sensor
    */
   private def getOrCreateQuotaSensors(clientId: String): ClientSensors = {
-
-    // Names of the sensors to access
-    val quotaSensorName = getQuotaSensorName(clientId)
-    val throttleTimeSensorName = getThrottleTimeSensorName(clientId)
-    var quotaSensor: Sensor = null
-    var throttleTimeSensor: Sensor = null
-
-    /* Acquire the read lock to fetch the sensors. It is safe to call getSensor from multiple threads.
-     * The read lock allows a thread to create a sensor in isolation. The thread creating the sensor
-     * will acquire the write lock and prevent the sensors from being read while they are being created.
-     * It should be sufficient to simply check if the sensor is null without acquiring a read lock but the
-     * sensor being present doesn't mean that it is fully initialized i.e. all the Metrics may not have been added.
-     * This read lock waits until the writer thread has released its lock i.e. fully initialized the sensor
-     * at which point it is safe to read
-     */
-    lock.readLock().lock()
-    try {
-      quotaSensor = metrics.getSensor(quotaSensorName)
-      throttleTimeSensor = metrics.getSensor(throttleTimeSensorName)
-    }
-    finally {
-      lock.readLock().unlock()
-    }
-
-    /* If the sensor is null, try to create it else return the created sensor
-     * Either of the sensors can be null, hence null checks on both
-     */
-    if (quotaSensor == null || throttleTimeSensor == null) {
-      /* Acquire a write lock because the sensor may not have been created and we only want one thread to create it.
-       * Note that multiple threads may acquire the write lock if they all see a null sensor initially
-       * In this case, the writer checks the sensor after acquiring the lock again.
-       * This is safe from Double Checked Locking because the references are read
-       * after acquiring read locks and hence they cannot see a partially published reference
-       */
-      lock.writeLock().lock()
-      try {
-        // Set the var for both sensors in case another thread has won the race to acquire the write lock. This will
-        // ensure that we initialise `ClientSensors` with non-null parameters.
-        quotaSensor = metrics.getSensor(quotaSensorName)
-        throttleTimeSensor = metrics.getSensor(throttleTimeSensorName)
-        if (throttleTimeSensor == null) {
-          // create the throttle time sensor also. Use default metric config
-          throttleTimeSensor = metrics.sensor(throttleTimeSensorName,
-                                              null,
-                                              ClientQuotaManagerConfig.InactiveSensorExpirationTimeSeconds)
-          throttleTimeSensor.add(metrics.metricName("throttle-time",
-                                                apiKey,
-                                                "Tracking average throttle-time per client",
-                                                "client-id",
-                                                clientId), new Avg())
-        }
-
-
-        if (quotaSensor == null) {
-          quotaSensor = metrics.sensor(quotaSensorName,
-                                       getQuotaMetricConfig(quota(clientId)),
-                                       ClientQuotaManagerConfig.InactiveSensorExpirationTimeSeconds)
-          quotaSensor.add(clientRateMetricName(clientId), new Rate())
-        }
-      } finally {
-        lock.writeLock().unlock()
-      }
-    }
-    // return the read or created sensors
-    ClientSensors(quotaSensor, throttleTimeSensor)
+    ClientSensors(
+      sensorAccessor.getOrCreate(
+        getQuotaSensorName(clientId),
+        ClientQuotaManagerConfig.InactiveSensorExpirationTimeSeconds,
+        lock, metrics,
+        () => clientRateMetricName(clientId),
+        () => getQuotaMetricConfig(quota(clientId)),
+        () => new Rate()
+      ),
+      sensorAccessor.getOrCreate(getThrottleTimeSensorName(clientId),
+        ClientQuotaManagerConfig.InactiveSensorExpirationTimeSeconds,
+        lock,
+        metrics,
+        () => metrics.metricName("throttle-time", apiKey.toString, "Tracking average throttle-time per client", "client-id", clientId),
+        () => null,
+        () => new Avg()
+      )
+    )
   }
 
   private def getThrottleTimeSensorName(clientId: String): String = apiKey + "ThrottleTime-" + clientId
@@ -272,12 +225,12 @@ class ClientQuotaManager(private val config: ClientQuotaManagerConfig,
       else
         this.overriddenQuota.put(clientId, quota)
 
-      // Change the underlying metric config if the sensor has been created
-      val allMetrics = metrics.metrics()
-      val quotaMetricName = clientRateMetricName(clientId)
-      if (allMetrics.containsKey(quotaMetricName)) {
+      // Change the underlying metric config if the sensor has been created.
+      // Note the metric could be expired by another thread, so use a local variable and null check.
+      val metric = metrics.metrics.get(clientRateMetricName(clientId))
+      if (metric != null) {
         logger.info(s"Sensor for clientId $clientId already exists. Changing quota to ${quota.bound()} in MetricConfig")
-        allMetrics.get(quotaMetricName).config(getQuotaMetricConfig(quota))
+        metric.config(getQuotaMetricConfig(quota))
       }
     } finally {
       lock.writeLock().unlock()
@@ -285,7 +238,7 @@ class ClientQuotaManager(private val config: ClientQuotaManagerConfig,
   }
 
   private def clientRateMetricName(clientId: String): MetricName = {
-    metrics.metricName("byte-rate", apiKey,
+    metrics.metricName("byte-rate", apiKey.toString,
                    "Tracking byte-rate per client",
                    "client-id", clientId)
   }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ConfigHandler.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ConfigHandler.scala b/core/src/main/scala/kafka/server/ConfigHandler.scala
index d07fdd8..67b74a7 100644
--- a/core/src/main/scala/kafka/server/ConfigHandler.scala
+++ b/core/src/main/scala/kafka/server/ConfigHandler.scala
@@ -21,25 +21,28 @@ import java.util.Properties
 
 import kafka.api.ApiVersion
 import kafka.log.{LogConfig, LogManager}
+import kafka.server.Constants._
+import kafka.server.KafkaConfig._
+import kafka.server.QuotaFactory.QuotaManagers
 import kafka.utils.Logging
+import org.apache.kafka.common.config.ConfigDef.Validator
+import org.apache.kafka.common.config.ConfigException
 import org.apache.kafka.common.metrics.Quota
-import org.apache.kafka.common.protocol.ApiKeys
-
-import scala.collection.Map
+import org.apache.kafka.common.metrics.Quota._
 import scala.collection.JavaConverters._
 
 /**
- * The ConfigHandler is used to process config change notifications received by the DynamicConfigManager
- */
+  * The ConfigHandler is used to process config change notifications received by the DynamicConfigManager
+  */
 trait ConfigHandler {
   def processConfigChanges(entityName: String, value: Properties)
 }
 
 /**
- * The TopicConfigHandler will process topic config changes in ZK.
- * The callback provides the topic name and the full properties set read from ZK
- */
-class TopicConfigHandler(private val logManager: LogManager, kafkaConfig: KafkaConfig) extends ConfigHandler with Logging {
+  * The TopicConfigHandler will process topic config changes in ZK.
+  * The callback provides the topic name and the full properties set read from ZK
+  */
+class TopicConfigHandler(private val logManager: LogManager, kafkaConfig: KafkaConfig, val quotas: QuotaManagers) extends ConfigHandler with Logging  {
 
   def processConfigChanges(topic: String, topicConfig: Properties) {
     // Validate the compatibility of message format version.
@@ -63,6 +66,33 @@ class TopicConfigHandler(private val logManager: LogManager, kafkaConfig: KafkaC
       val logConfig = LogConfig(props)
       logs.foreach(_.config = logConfig)
     }
+
+    val brokerId = kafkaConfig.brokerId
+
+    if (topicConfig.containsKey(LogConfig.ThrottledReplicasListProp) && topicConfig.getProperty(LogConfig.ThrottledReplicasListProp).length > 0) {
+      val partitions = parseThrottledPartitions(topicConfig, brokerId)
+      quotas.leader.markThrottled(topic, partitions)
+      quotas.follower.markThrottled(topic, partitions)
+      logger.debug(s"Setting throttled partitions on broker $brokerId for topic: $topic and partitions $partitions")
+    } else {
+      quotas.leader.removeThrottle(topic)
+      quotas.follower.removeThrottle(topic)
+      logger.debug(s"Removing throttled partitions from broker $brokerId for topic $topic")
+    }
+  }
+
+  def parseThrottledPartitions(topicConfig: Properties, brokerId: Int): Seq[Int] = {
+    val configValue = topicConfig.get(LogConfig.ThrottledReplicasListProp).toString.trim
+    ThrottledReplicaValidator.ensureValid(LogConfig.ThrottledReplicasListProp, configValue)
+    configValue.trim match {
+      case "" => Seq()
+      case "*" => AllReplicas
+      case _ => configValue.trim
+        .split(",")
+        .map(_.split(":"))
+        .filter(_ (1).toInt == brokerId) //Filter this replica
+        .map(_ (0).toInt).toSeq //convert to list of partition ids
+    }
   }
 }
 
@@ -72,25 +102,53 @@ object ClientConfigOverride {
 }
 
 /**
- * The ClientIdConfigHandler will process clientId config changes in ZK.
- * The callback provides the clientId and the full properties set read from ZK.
- * This implementation reports the overrides to the respective ClientQuotaManager objects
- */
-class ClientIdConfigHandler(private val quotaManagers: Map[Short, ClientQuotaManager]) extends ConfigHandler {
-
-  def processConfigChanges(clientId: String, clientConfig: Properties) = {
+  * The ClientIdConfigHandler will process clientId config changes in ZK.
+  * The callback provides the clientId and the full properties set read from ZK.
+  * This implementation reports the overrides to the respective ClientQuotaManager objects
+  */
+class ClientIdConfigHandler(private val quotaManagers: QuotaManagers) extends ConfigHandler {
+  def processConfigChanges(clientId: String, clientConfig: Properties) {
     if (clientConfig.containsKey(ClientConfigOverride.ProducerOverride)) {
-      quotaManagers(ApiKeys.PRODUCE.id).updateQuota(clientId,
+      quotaManagers.produce.updateQuota(clientId,
         new Quota(clientConfig.getProperty(ClientConfigOverride.ProducerOverride).toLong, true))
     } else {
-      quotaManagers(ApiKeys.PRODUCE.id).resetQuota(clientId)
+      quotaManagers.fetch.resetQuota(clientId)
     }
 
     if (clientConfig.containsKey(ClientConfigOverride.ConsumerOverride)) {
-      quotaManagers(ApiKeys.FETCH.id).updateQuota(clientId,
+      quotaManagers.fetch.updateQuota(clientId,
         new Quota(clientConfig.getProperty(ClientConfigOverride.ConsumerOverride).toLong, true))
     } else {
-      quotaManagers(ApiKeys.FETCH.id).resetQuota(clientId)
+      quotaManagers.produce.resetQuota(clientId)
+    }
+  }
+}
+
+/**
+  * The BrokerConfigHandler will process individual broker config changes in ZK.
+  * The callback provides the brokerId and the full properties set read from ZK.
+  * This implementation reports the overrides to the respective ReplicationQuotaManager objects
+  */
+class BrokerConfigHandler(private val brokerConfig: KafkaConfig, private val quotaManagers: QuotaManagers) extends ConfigHandler with Logging {
+  def processConfigChanges(brokerId: String, properties: Properties) {
+    if (brokerConfig.brokerId == brokerId.trim.toInt) {
+      val limit = if (properties.containsKey(ThrottledReplicationRateLimitProp)) properties.getProperty(ThrottledReplicationRateLimitProp).toLong else Defaults.ThrottledReplicationRateLimit
+      quotaManagers.leader.updateQuota(upperBound(limit))
+      quotaManagers.follower.updateQuota(upperBound(limit))
     }
   }
 }
+
+object ThrottledReplicaValidator extends Validator {
+  override def ensureValid(name: String, value: scala.Any): Unit = {
+    value match {
+      case s: String => if (!isValid(s))
+        throw new ConfigException(name, value, s"$name  must match for format [partitionId],[brokerId]:[partitionId],[brokerId]:[partitionId],[brokerId] etc")
+      case _ => throw new ConfigException(name, value, s"$name  must be a string")
+    }
+  }
+
+  private def isValid(proposed: String): Boolean = {
+    proposed.trim.equals("*") || proposed.trim.matches("([0-9]+:[0-9]+)?(,[0-9]+:[0-9]+)*")
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/DelayedFetch.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/DelayedFetch.scala b/core/src/main/scala/kafka/server/DelayedFetch.scala
index a0ff00d..cf3a48f 100644
--- a/core/src/main/scala/kafka/server/DelayedFetch.scala
+++ b/core/src/main/scala/kafka/server/DelayedFetch.scala
@@ -54,6 +54,7 @@ case class FetchMetadata(fetchMinBytes: Int,
 class DelayedFetch(delayMs: Long,
                    fetchMetadata: FetchMetadata,
                    replicaManager: ReplicaManager,
+                   quota: ReplicaQuota,
                    responseCallback: Map[TopicAndPartition, FetchResponsePartitionData] => Unit)
   extends DelayedOperation(delayMs) {
 
@@ -69,6 +70,7 @@ class DelayedFetch(delayMs: Long,
    */
   override def tryComplete() : Boolean = {
     var accumulatedSize = 0
+    var accumulatedThrottledSize = 0
     fetchMetadata.fetchPartitionStatus.foreach {
       case (topicAndPartition, fetchStatus) =>
         val fetchOffset = fetchStatus.startOffsetMetadata
@@ -93,10 +95,15 @@ class DelayedFetch(delayMs: Long,
                 // Case C, this can happen when the fetch operation is falling behind the current segment
                 // or the partition has just rolled a new segment
                 debug("Satisfying fetch %s immediately since it is fetching older segments.".format(fetchMetadata))
-                return forceComplete()
+                if (!(quota.isThrottled(topicAndPartition) && quota.isQuotaExceeded()))
+                  return forceComplete()
               } else if (fetchOffset.messageOffset < endOffset.messageOffset) {
-                // we need take the partition fetch size as upper bound when accumulating the bytes
-                accumulatedSize += math.min(endOffset.positionDiff(fetchOffset), fetchStatus.fetchInfo.fetchSize)
+                // we take the partition fetch size as upper bound when accumulating the bytes (skip if a throttled partition)
+                val bytesAvailable = math.min(endOffset.positionDiff(fetchOffset), fetchStatus.fetchInfo.fetchSize)
+                if (quota.isThrottled(topicAndPartition))
+                  accumulatedThrottledSize += bytesAvailable
+                else
+                  accumulatedSize += bytesAvailable
               }
             }
           }
@@ -111,7 +118,8 @@ class DelayedFetch(delayMs: Long,
     }
 
     // Case D
-    if (accumulatedSize >= fetchMetadata.fetchMinBytes)
+    if (accumulatedSize >= fetchMetadata.fetchMinBytes
+      || ((accumulatedSize + accumulatedThrottledSize) >= fetchMetadata.fetchMinBytes && !quota.isQuotaExceeded()))
       forceComplete()
     else
       false
@@ -130,7 +138,7 @@ class DelayedFetch(delayMs: Long,
   override def onComplete() {
     val logReadResults = replicaManager.readFromLocalLog(fetchMetadata.fetchOnlyLeader,
       fetchMetadata.fetchOnlyCommitted,
-      fetchMetadata.fetchPartitionStatus.mapValues(status => status.fetchInfo))
+      fetchMetadata.fetchPartitionStatus.mapValues(status => status.fetchInfo), quota)
 
     val fetchPartitionData = logReadResults.mapValues(result =>
       FetchResponsePartitionData(result.errorCode, result.hw, result.info.messageSet))

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/DynamicConfigManager.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/DynamicConfigManager.scala b/core/src/main/scala/kafka/server/DynamicConfigManager.scala
index eb406af..556534a 100644
--- a/core/src/main/scala/kafka/server/DynamicConfigManager.scala
+++ b/core/src/main/scala/kafka/server/DynamicConfigManager.scala
@@ -37,6 +37,8 @@ import org.I0Itec.zkclient.{IZkStateListener, IZkChildListener, ZkClient}
 object ConfigType {
   val Topic = "topics"
   val Client = "clients"
+  val Broker = "brokers"
+  val all = Seq(Topic, Client, Broker)
 }
 
 /**
@@ -92,8 +94,8 @@ class DynamicConfigManager(private val zkUtils: ZkUtils,
           val entityType = map.get("entity_type") match {
             case Some(ConfigType.Topic) => ConfigType.Topic
             case Some(ConfigType.Client) => ConfigType.Client
-            case _ => throw new IllegalArgumentException("Config change notification must have 'entity_type' set to either 'client' or 'topic'." +
-              " Received: " + json)
+            case Some(ConfigType.Broker) => ConfigType.Broker
+            case _ => throw new IllegalArgumentException(s"Config change notification must have 'entity_type' set to one of ${ConfigType.all}. Received: $json")
           }
 
           val entity = map.get("entity_name") match {

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/KafkaApis.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 0a5258e..677b5dd 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -24,6 +24,7 @@ import java.util.Properties
 import kafka.admin.{AdminUtils, RackAwareMode}
 import kafka.api._
 import kafka.cluster.Partition
+import kafka.server.QuotaFactory.{UnboundedQuota, QuotaManagers}
 import kafka.common
 import kafka.common._
 import kafka.controller.KafkaController
@@ -34,8 +35,9 @@ import kafka.network._
 import kafka.network.RequestChannel.{Response, Session}
 import kafka.security.auth
 import kafka.security.auth.{Authorizer, ClusterAction, Create, Describe, Group, Operation, Read, Resource, Write, Delete}
+import kafka.server.QuotaType._
 import kafka.utils.{Logging, SystemTime, ZKGroupTopicDirs, ZkUtils}
-import org.apache.kafka.common.errors.{ClusterAuthorizationException, InvalidTopicException, NotLeaderForPartitionException, UnknownTopicOrPartitionException, TopicExistsException}
+import org.apache.kafka.common.errors.{ClusterAuthorizationException, NotLeaderForPartitionException, UnknownTopicOrPartitionException, TopicExistsException}
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors, Protocol, SecurityProtocol}
 import org.apache.kafka.common.requests.{ApiVersionsResponse, DescribeGroupsRequest, DescribeGroupsResponse, GroupCoordinatorRequest, GroupCoordinatorResponse, HeartbeatRequest, HeartbeatResponse, JoinGroupRequest, JoinGroupResponse, LeaderAndIsrRequest, LeaderAndIsrResponse, LeaveGroupRequest, LeaveGroupResponse, ListGroupsResponse, ListOffsetRequest, ListOffsetResponse, MetadataRequest, MetadataResponse, OffsetCommitRequest, OffsetCommitResponse, OffsetFetchRequest, OffsetFetchResponse, ProduceRequest, ProduceResponse, ResponseHeader, ResponseSend, StopReplicaRequest, StopReplicaResponse, SyncGroupRequest, SyncGroupResponse, UpdateMetadataRequest, UpdateMetadataResponse, CreateTopicsRequest, CreateTopicsResponse, DeleteTopicsRequest, DeleteTopicsResponse}
@@ -60,11 +62,10 @@ class KafkaApis(val requestChannel: RequestChannel,
                 val config: KafkaConfig,
                 val metadataCache: MetadataCache,
                 val metrics: Metrics,
-                val authorizer: Option[Authorizer]) extends Logging {
+                val authorizer: Option[Authorizer],
+                val quotas: QuotaManagers) extends Logging {
 
   this.logIdent = "[KafkaApi-%d] ".format(brokerId)
-  // Store all the quota managers for each type of request
-  val quotaManagers: Map[Short, ClientQuotaManager] = instantiateQuotaManagers(config)
 
   /**
    * Top-level method that handles all requests and multiplexes to the right api
@@ -144,7 +145,7 @@ class KafkaApis(val requestChannel: RequestChannel,
       val responseHeader = new ResponseHeader(correlationId)
       val leaderAndIsrResponse =
         if (authorize(request.session, ClusterAction, Resource.ClusterResource)) {
-          val result = replicaManager.becomeLeaderOrFollower(correlationId, leaderAndIsrRequest, metadataCache, onLeadershipChange)
+          val  result = replicaManager.becomeLeaderOrFollower(correlationId, leaderAndIsrRequest, metadataCache, onLeadershipChange)
           new LeaderAndIsrResponse(result.errorCode, result.responseMap.mapValues(new JShort(_)).asJava)
         } else {
           val result = leaderAndIsrRequest.partitionStates.asScala.keys.map((_, new JShort(Errors.CLUSTER_AUTHORIZATION_FAILED.code))).toMap
@@ -393,7 +394,7 @@ class KafkaApis(val requestChannel: RequestChannel,
       // When this callback is triggered, the remote API call has completed
       request.apiRemoteCompleteTimeMs = SystemTime.milliseconds
 
-      quotaManagers(ApiKeys.PRODUCE.id).recordAndMaybeThrottle(
+      quotas.produce.recordAndMaybeThrottle(
         request.header.clientId,
         numBytesAppended,
         produceResponseCallback)
@@ -482,18 +483,17 @@ class KafkaApis(val requestChannel: RequestChannel,
         requestChannel.sendResponse(new RequestChannel.Response(request, new FetchResponseSend(request.connectionId, response)))
       }
 
-
       // When this callback is triggered, the remote API call has completed
       request.apiRemoteCompleteTimeMs = SystemTime.milliseconds
 
-      // Do not throttle replication traffic
       if (fetchRequest.isFromFollower) {
+        //We've already evaluated against the quota and are good to go. Just need to record it now.
+        val size = sizeOfThrottledPartitions(fetchRequest, mergedPartitionData, quotas.leader)
+        quotas.leader.record(size)
         fetchResponseCallback(0)
       } else {
-        quotaManagers(ApiKeys.FETCH.id).recordAndMaybeThrottle(fetchRequest.clientId,
-                                                               FetchResponse.responseSize(mergedPartitionData.groupBy(_._1.topic),
-                                                                                          fetchRequest.versionId),
-                                                               fetchResponseCallback)
+        val size = FetchResponse.responseSize(mergedPartitionData.groupBy(_._1.topic), fetchRequest.versionId)
+        quotas.fetch.recordAndMaybeThrottle(fetchRequest.clientId, size, fetchResponseCallback)
       }
     }
 
@@ -506,10 +506,19 @@ class KafkaApis(val requestChannel: RequestChannel,
         fetchRequest.replicaId,
         fetchRequest.minBytes,
         authorizedRequestInfo,
+        replicationQuota(fetchRequest),
         sendResponseCallback)
     }
   }
 
+  private def sizeOfThrottledPartitions(fetchRequest: FetchRequest, mergedPartitionData: Map[TopicAndPartition, FetchResponsePartitionData], quota: ReplicationQuotaManager): Int = {
+    val throttledPartitions = mergedPartitionData.filter { case (partition, _) => quota.isThrottled(partition) }
+    FetchResponse.responseSize(throttledPartitions.groupBy(_._1.topic), fetchRequest.versionId)
+  }
+
+  def replicationQuota(fetchRequest: FetchRequest): ReplicaQuota =
+    if (fetchRequest.isFromFollower) quotas.leader else UnboundedQuota
+
   /**
    * Handle an offset request
    */
@@ -976,31 +985,6 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
   }
 
-  /*
-   * Returns a Map of all quota managers configured. The request Api key is the key for the Map
-   */
-  private def instantiateQuotaManagers(cfg: KafkaConfig): Map[Short, ClientQuotaManager] = {
-    val producerQuotaManagerCfg = ClientQuotaManagerConfig(
-      quotaBytesPerSecondDefault = cfg.producerQuotaBytesPerSecondDefault,
-      numQuotaSamples = cfg.numQuotaSamples,
-      quotaWindowSizeSeconds = cfg.quotaWindowSizeSeconds
-    )
-
-    val consumerQuotaManagerCfg = ClientQuotaManagerConfig(
-      quotaBytesPerSecondDefault = cfg.consumerQuotaBytesPerSecondDefault,
-      numQuotaSamples = cfg.numQuotaSamples,
-      quotaWindowSizeSeconds = cfg.quotaWindowSizeSeconds
-    )
-
-    val quotaManagers = Map[Short, ClientQuotaManager](
-      ApiKeys.PRODUCE.id ->
-              new ClientQuotaManager(producerQuotaManagerCfg, metrics, ApiKeys.PRODUCE.name, new org.apache.kafka.common.utils.SystemTime),
-      ApiKeys.FETCH.id ->
-              new ClientQuotaManager(consumerQuotaManagerCfg, metrics, ApiKeys.FETCH.name, new org.apache.kafka.common.utils.SystemTime)
-    )
-    quotaManagers
-  }
-
   def handleLeaveGroupRequest(request: RequestChannel.Request) {
     val leaveGroupRequest = request.body.asInstanceOf[LeaveGroupRequest]
     val respHeader = new ResponseHeader(request.header.correlationId)
@@ -1047,9 +1031,7 @@ class KafkaApis(val requestChannel: RequestChannel,
   }
 
   def close() {
-    quotaManagers.foreach { case (apiKey, quotaManager) =>
-      quotaManager.shutdown()
-    }
+    quotas.shutdown()
     info("Shutdown complete.")
   }
 

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/KafkaConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/KafkaConfig.scala b/core/src/main/scala/kafka/server/KafkaConfig.scala
index 531ee62..3671297 100755
--- a/core/src/main/scala/kafka/server/KafkaConfig.scala
+++ b/core/src/main/scala/kafka/server/KafkaConfig.scala
@@ -18,7 +18,6 @@
 package kafka.server
 
 import java.util.Properties
-
 import kafka.api.{ApiVersion, KAFKA_0_10_0_IV1}
 import kafka.cluster.EndPoint
 import kafka.consumer.ConsumerConfig
@@ -104,6 +103,7 @@ object Defaults {
   val NumRecoveryThreadsPerDataDir = 1
   val AutoCreateTopicsEnable = true
   val MinInSyncReplicas = 1
+  val ThrottledReplicationRateLimit = Long.MaxValue
 
   /** ********* Replication configuration ***********/
   val ControllerSocketTimeoutMs = RequestTimeoutMs
@@ -153,6 +153,8 @@ object Defaults {
   val ConsumerQuotaBytesPerSecondDefault = ClientQuotaManagerConfig.QuotaBytesPerSecondDefault
   val NumQuotaSamples: Int = ClientQuotaManagerConfig.DefaultNumQuotaSamples
   val QuotaWindowSizeSeconds: Int = ClientQuotaManagerConfig.DefaultQuotaWindowSizeSeconds
+  val NumReplicationQuotaSamples: Int = ReplicationQuotaManagerConfig.DefaultNumQuotaSamples
+  val ReplicationQuotaWindowSizeSeconds: Int = ReplicationQuotaManagerConfig.DefaultQuotaWindowSizeSeconds
 
   val DeleteTopicEnable = false
 
@@ -313,7 +315,10 @@ object KafkaConfig {
   val ProducerQuotaBytesPerSecondDefaultProp = "quota.producer.default"
   val ConsumerQuotaBytesPerSecondDefaultProp = "quota.consumer.default"
   val NumQuotaSamplesProp = "quota.window.num"
+  val NumReplicationQuotaSamplesProp = "replication.quota.window.num"
   val QuotaWindowSizeSecondsProp = "quota.window.size.seconds"
+  val ReplicationQuotaWindowSizeSecondsProp = "replication.quota.window.size.seconds"
+  val ThrottledReplicationRateLimitProp = "replication.quota.throttled.rate"
 
   val DeleteTopicEnableProp = "delete.topic.enable"
   val CompressionTypeProp = "compression.type"
@@ -520,8 +525,12 @@ object KafkaConfig {
   /** ********* Quota Configuration ***********/
   val ProducerQuotaBytesPerSecondDefaultDoc = "Any producer distinguished by clientId will get throttled if it produces more bytes than this value per-second"
   val ConsumerQuotaBytesPerSecondDefaultDoc = "Any consumer distinguished by clientId/consumer group will get throttled if it fetches more bytes than this value per-second"
-  val NumQuotaSamplesDoc = "The number of samples to retain in memory"
-  val QuotaWindowSizeSecondsDoc = "The time span of each sample"
+  val NumQuotaSamplesDoc = "The number of samples to retain in memory for client quotas"
+  val NumReplicationQuotaSamplesDoc = "The number of samples to retain in memory for replication quotas"
+  val QuotaWindowSizeSecondsDoc = "The time span of each sample for client quotas"
+  val ReplicationQuotaWindowSizeSecondsDoc = "The time span of each sample for replication quotas"
+  val ThrottledReplicationRateLimitDoc = "A long representing the upper bound (bytes/sec) on replication traffic for replicas enumerated in the " +
+    s"property $ThrottledReplicationRateLimitProp. This property can be only set dynamically via the config command."
 
   val DeleteTopicEnableDoc = "Enables delete topic. Delete topic through the admin tool will have no effect if this config is turned off"
   val CompressionTypeDoc = "Specify the final compression type for a given topic. This configuration accepts the standard compression codecs " +
@@ -562,6 +571,8 @@ object KafkaConfig {
   val SaslKerberosMinTimeBeforeReloginDoc = SaslConfigs.SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN_DOC
   val SaslKerberosPrincipalToLocalRulesDoc = SaslConfigs.SASL_KERBEROS_PRINCIPAL_TO_LOCAL_RULES_DOC
 
+  def dynamicBrokerConfigs = Seq(KafkaConfig.ThrottledReplicationRateLimitProp)
+
   private val configDef = {
     import ConfigDef.Importance._
     import ConfigDef.Range._
@@ -705,8 +716,10 @@ object KafkaConfig {
       .define(ProducerQuotaBytesPerSecondDefaultProp, LONG, Defaults.ProducerQuotaBytesPerSecondDefault, atLeast(1), HIGH, ProducerQuotaBytesPerSecondDefaultDoc)
       .define(ConsumerQuotaBytesPerSecondDefaultProp, LONG, Defaults.ConsumerQuotaBytesPerSecondDefault, atLeast(1), HIGH, ConsumerQuotaBytesPerSecondDefaultDoc)
       .define(NumQuotaSamplesProp, INT, Defaults.NumQuotaSamples, atLeast(1), LOW, NumQuotaSamplesDoc)
+      .define(NumReplicationQuotaSamplesProp, INT, Defaults.NumReplicationQuotaSamples, atLeast(1), LOW, NumReplicationQuotaSamplesDoc)
       .define(QuotaWindowSizeSecondsProp, INT, Defaults.QuotaWindowSizeSeconds, atLeast(1), LOW, QuotaWindowSizeSecondsDoc)
-
+      .define(ReplicationQuotaWindowSizeSecondsProp, INT, Defaults.ReplicationQuotaWindowSizeSeconds, atLeast(1), LOW, ReplicationQuotaWindowSizeSecondsDoc)
+      .define(ThrottledReplicationRateLimitProp, LONG, Defaults.ThrottledReplicationRateLimit, atLeast(0), MEDIUM, ThrottledReplicationRateLimitDoc)
 
       /** ********* SSL Configuration ****************/
       .define(PrincipalBuilderClassProp, CLASS, Defaults.PrincipalBuilderClass, MEDIUM, PrincipalBuilderClassDoc)
@@ -751,7 +764,7 @@ object KafkaConfig {
     import scala.collection.JavaConversions._
     val names = configDef.names()
     for (name <- props.keys)
-      require(names.contains(name), "Unknown configuration \"%s\".".format(name))
+      require(names.contains(name), "Unknown Kafka configuration \"%s\".".format(name))
   }
 
   def fromProps(props: Properties): KafkaConfig =
@@ -938,6 +951,8 @@ class KafkaConfig(val props: java.util.Map[_, _], doLog: Boolean) extends Abstra
   val consumerQuotaBytesPerSecondDefault = getLong(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp)
   val numQuotaSamples = getInt(KafkaConfig.NumQuotaSamplesProp)
   val quotaWindowSizeSeconds = getInt(KafkaConfig.QuotaWindowSizeSecondsProp)
+  val numReplicationQuotaSamples = getInt(KafkaConfig.NumReplicationQuotaSamplesProp)
+  val replicationQuotaWindowSizeSeconds = getInt(KafkaConfig.ReplicationQuotaWindowSizeSecondsProp)
 
   val deleteTopicEnable = getBoolean(KafkaConfig.DeleteTopicEnableProp)
   val compressionType = getString(KafkaConfig.CompressionTypeProp)

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/KafkaServer.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/KafkaServer.scala b/core/src/main/scala/kafka/server/KafkaServer.scala
index b83a3ee..4509e37 100755
--- a/core/src/main/scala/kafka/server/KafkaServer.scala
+++ b/core/src/main/scala/kafka/server/KafkaServer.scala
@@ -41,7 +41,7 @@ import org.apache.kafka.common.requests.{ControlledShutdownResponse, ControlledS
 import org.apache.kafka.common.security.JaasUtils
 import org.apache.kafka.common.utils.AppInfoParser
 
-import scala.collection.mutable
+import scala.collection.{Map, mutable}
 import scala.collection.JavaConverters._
 import org.I0Itec.zkclient.ZkClient
 import kafka.controller.{ControllerStats, KafkaController}
@@ -133,6 +133,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime, threadNamePr
 
   var kafkaHealthcheck: KafkaHealthcheck = null
   var metadataCache: MetadataCache = null
+  var quotaManagers: QuotaFactory.QuotaManagers = null
 
   var zkUtils: ZkUtils = null
   val correlationId: AtomicInteger = new AtomicInteger(0)
@@ -172,6 +173,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime, threadNamePr
       val canStartup = isStartingUp.compareAndSet(false, true)
       if (canStartup) {
         metrics = new Metrics(metricConfig, reporters, kafkaMetricsTime, true)
+        quotaManagers = QuotaFactory.instantiate(config, metrics, time)
 
         brokerState.newState(Starting)
 
@@ -196,7 +198,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime, threadNamePr
 
         /* start replica manager */
         replicaManager = new ReplicaManager(config, metrics, time, kafkaMetricsTime, zkUtils, kafkaScheduler, logManager,
-          isShuttingDown)
+          isShuttingDown, quotaManagers.follower)
         replicaManager.startup()
 
         /* start kafka controller */
@@ -218,14 +220,15 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime, threadNamePr
 
         /* start processing requests */
         apis = new KafkaApis(socketServer.requestChannel, replicaManager, adminManager, groupCoordinator,
-          kafkaController, zkUtils, config.brokerId, config, metadataCache, metrics, authorizer)
+          kafkaController, zkUtils, config.brokerId, config, metadataCache, metrics, authorizer, quotaManagers)
         requestHandlerPool = new KafkaRequestHandlerPool(config.brokerId, socketServer.requestChannel, apis, config.numIoThreads)
 
         Mx4jLoader.maybeLoad()
 
         /* start dynamic config manager */
-        dynamicConfigHandlers = Map[String, ConfigHandler](ConfigType.Topic -> new TopicConfigHandler(logManager, config),
-                                                           ConfigType.Client -> new ClientIdConfigHandler(apis.quotaManagers))
+        dynamicConfigHandlers = Map[String, ConfigHandler](ConfigType.Topic -> new TopicConfigHandler(logManager, config, quotaManagers),
+                                                           ConfigType.Client -> new ClientIdConfigHandler(quotaManagers),
+                                                           ConfigType.Broker -> new BrokerConfigHandler(config, quotaManagers))
 
         // Apply all existing client configs to the ClientIdConfigHandler to bootstrap the overrides
         // TODO: Move this logic to DynamicConfigManager
@@ -633,6 +636,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime, threadNamePr
     * <li> config has broker.id and meta.properties contains broker.id if they don't match throws InconsistentBrokerIdException
     * <li> config has broker.id and there is no meta.properties file, creates new meta.properties and stores broker.id
     * <ol>
+    *
     * @return A brokerId.
     */
   private def getBrokerId: Int =  {


[2/3] kafka git commit: KAFKA-1464; Add a throttling option to the Kafka replication

Posted by ju...@apache.org.
http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/QuotaFactory.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/QuotaFactory.scala b/core/src/main/scala/kafka/server/QuotaFactory.scala
new file mode 100644
index 0000000..65e7c9e
--- /dev/null
+++ b/core/src/main/scala/kafka/server/QuotaFactory.scala
@@ -0,0 +1,74 @@
+/**
+  * 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.
+  */
+package kafka.server
+
+import kafka.common.TopicAndPartition
+import kafka.server.QuotaType._
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.utils.Time
+
+object QuotaType  {
+  case object Fetch extends QuotaType
+  case object Produce extends QuotaType
+  case object LeaderReplication extends QuotaType
+  case object FollowerReplication extends QuotaType
+}
+sealed trait QuotaType
+
+object QuotaFactory {
+
+  object UnboundedQuota extends ReplicaQuota {
+    override def isThrottled(topicAndPartition: TopicAndPartition): Boolean = false
+    override def isQuotaExceeded(): Boolean = false
+  }
+
+  case class QuotaManagers(fetch: ClientQuotaManager, produce: ClientQuotaManager, leader: ReplicationQuotaManager, follower: ReplicationQuotaManager) {
+    def shutdown() {
+      fetch.shutdown
+      produce.shutdown
+    }
+  }
+
+  def instantiate(cfg: KafkaConfig, metrics: Metrics, time: Time): QuotaManagers = {
+    QuotaManagers(
+      new ClientQuotaManager(clientFetchConfig(cfg), metrics, Fetch, time),
+      new ClientQuotaManager(clientProduceConfig(cfg), metrics, Produce, time),
+      new ReplicationQuotaManager(replicationConfig(cfg), metrics, LeaderReplication, time),
+      new ReplicationQuotaManager(replicationConfig(cfg), metrics, FollowerReplication, time)
+    )
+  }
+
+  def clientProduceConfig(cfg: KafkaConfig): ClientQuotaManagerConfig =
+    ClientQuotaManagerConfig(
+      quotaBytesPerSecondDefault = cfg.producerQuotaBytesPerSecondDefault,
+      numQuotaSamples = cfg.numQuotaSamples,
+      quotaWindowSizeSeconds = cfg.quotaWindowSizeSeconds
+    )
+
+  def clientFetchConfig(cfg: KafkaConfig): ClientQuotaManagerConfig =
+    ClientQuotaManagerConfig(
+      quotaBytesPerSecondDefault = cfg.consumerQuotaBytesPerSecondDefault,
+      numQuotaSamples = cfg.numQuotaSamples,
+      quotaWindowSizeSeconds = cfg.quotaWindowSizeSeconds
+    )
+
+  def replicationConfig(cfg: KafkaConfig): ReplicationQuotaManagerConfig =
+    ReplicationQuotaManagerConfig(
+      numQuotaSamples = cfg.numReplicationQuotaSamples,
+      quotaWindowSizeSeconds = cfg.replicationQuotaWindowSizeSeconds
+    )
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ReplicaFetcherManager.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ReplicaFetcherManager.scala b/core/src/main/scala/kafka/server/ReplicaFetcherManager.scala
index 96c2a38..3894d9b 100644
--- a/core/src/main/scala/kafka/server/ReplicaFetcherManager.scala
+++ b/core/src/main/scala/kafka/server/ReplicaFetcherManager.scala
@@ -21,9 +21,9 @@ import kafka.cluster.BrokerEndPoint
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.utils.Time
 
-class ReplicaFetcherManager(brokerConfig: KafkaConfig, replicaMgr: ReplicaManager, metrics: Metrics, time: Time, threadNamePrefix: Option[String] = None)
-        extends AbstractFetcherManager("ReplicaFetcherManager on broker " + brokerConfig.brokerId,
-                                       "Replica", brokerConfig.numReplicaFetchers) {
+class ReplicaFetcherManager(brokerConfig: KafkaConfig, replicaMgr: ReplicaManager, metrics: Metrics, time: Time, threadNamePrefix: Option[String] = None, quotaManager: ReplicationQuotaManager)
+      extends AbstractFetcherManager("ReplicaFetcherManager on broker " + brokerConfig.brokerId,
+        "Replica", brokerConfig.numReplicaFetchers) {
 
   override def createFetcherThread(fetcherId: Int, sourceBroker: BrokerEndPoint): AbstractFetcherThread = {
     val threadName = threadNamePrefix match {
@@ -33,12 +33,12 @@ class ReplicaFetcherManager(brokerConfig: KafkaConfig, replicaMgr: ReplicaManage
         "%s:ReplicaFetcherThread-%d-%d".format(p, fetcherId, sourceBroker.id)
     }
     new ReplicaFetcherThread(threadName, fetcherId, sourceBroker, brokerConfig,
-      replicaMgr, metrics, time)
+      replicaMgr, metrics, time, quotaManager)
   }
 
   def shutdown() {
     info("shutting down")
     closeAllFetchers()
     info("shutdown completed")
-  }  
+  }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ReplicaFetcherThread.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ReplicaFetcherThread.scala b/core/src/main/scala/kafka/server/ReplicaFetcherThread.scala
index ef602e4..b0bd070 100644
--- a/core/src/main/scala/kafka/server/ReplicaFetcherThread.scala
+++ b/core/src/main/scala/kafka/server/ReplicaFetcherThread.scala
@@ -26,11 +26,10 @@ import kafka.message.ByteBufferMessageSet
 import kafka.api.{KAFKA_0_10_0_IV0, KAFKA_0_9_0}
 import kafka.common.{KafkaStorageException, TopicAndPartition}
 import ReplicaFetcherThread._
+
 import org.apache.kafka.clients.{ManualMetadataUpdater, NetworkClient, ClientRequest, ClientResponse}
 import org.apache.kafka.common.network.{LoginType, Selectable, ChannelBuilders, NetworkReceive, Selector, Mode}
-import org.apache.kafka.common.requests.{ListOffsetResponse, FetchResponse, RequestSend, AbstractRequest, ListOffsetRequest}
-import org.apache.kafka.common.requests.{FetchRequest => JFetchRequest}
-import org.apache.kafka.common.security.ssl.SslFactory
+import org.apache.kafka.common.requests.{FetchRequest => JFetchRequest, _}
 import org.apache.kafka.common.{Node, TopicPartition}
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{Errors, ApiKeys}
@@ -45,7 +44,9 @@ class ReplicaFetcherThread(name: String,
                            brokerConfig: KafkaConfig,
                            replicaMgr: ReplicaManager,
                            metrics: Metrics,
-                           time: Time)
+                           time: Time,
+                           quota: ReplicationQuotaManager
+                          )
   extends AbstractFetcherThread(name = name,
                                 clientId = name,
                                 sourceBroker = sourceBroker,
@@ -134,6 +135,8 @@ class ReplicaFetcherThread(name: String,
       if (logger.isTraceEnabled)
         trace("Follower %d set replica high watermark for partition [%s,%d] to %s"
           .format(replica.brokerId, topic, partitionId, followerHighWatermark))
+      if (quota.isThrottled(topicAndPartition))
+        quota.record(messageSet.sizeInBytes)
     } catch {
       case e: KafkaStorageException =>
         fatal(s"Disk error while replicating data for $topicAndPartition", e)
@@ -249,7 +252,6 @@ class ReplicaFetcherThread(name: String,
         networkClient.close(sourceBroker.id.toString)
         throw e
     }
-
   }
 
   private def earliestOrLatestOffset(topicAndPartition: TopicAndPartition, earliestOrLatest: Long, consumerId: Int): Long = {
@@ -269,15 +271,13 @@ class ReplicaFetcherThread(name: String,
 
   protected def buildFetchRequest(partitionMap: Map[TopicAndPartition, PartitionFetchState]): FetchRequest = {
     val requestMap = mutable.Map.empty[TopicPartition, JFetchRequest.PartitionData]
-
-    partitionMap.foreach { case ((TopicAndPartition(topic, partition), partitionFetchState)) =>
-      if (partitionFetchState.isActive)
-        requestMap(new TopicPartition(topic, partition)) = new JFetchRequest.PartitionData(partitionFetchState.offset, fetchSize)
+    val quotaExceeded = quota.isQuotaExceeded
+    partitionMap.foreach { case ((partition, partitionFetchState)) =>
+      if (partitionFetchState.isActive && !(quota.isThrottled(partition) && quotaExceeded))
+        requestMap(new TopicPartition(partition.topic, partition.partition)) = new JFetchRequest.PartitionData(partitionFetchState.offset, fetchSize)
     }
-
     new FetchRequest(new JFetchRequest(replicaId, maxWait, minBytes, requestMap.asJava))
   }
-
 }
 
 object ReplicaFetcherThread {

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ReplicaManager.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ReplicaManager.scala b/core/src/main/scala/kafka/server/ReplicaManager.scala
index f1cc694..f72df9a 100644
--- a/core/src/main/scala/kafka/server/ReplicaManager.scala
+++ b/core/src/main/scala/kafka/server/ReplicaManager.scala
@@ -28,6 +28,7 @@ import kafka.controller.KafkaController
 import kafka.log.{LogAppendInfo, LogManager}
 import kafka.message.{ByteBufferMessageSet, InvalidMessageException, Message, MessageSet}
 import kafka.metrics.KafkaMetricsGroup
+import kafka.server.QuotaFactory.UnboundedQuota
 import kafka.utils._
 import org.apache.kafka.common.errors.{ControllerMovedException, CorruptRecordException, InvalidTimestampException,
                                         InvalidTopicException, NotLeaderForPartitionException, OffsetOutOfRangeException,
@@ -108,7 +109,9 @@ class ReplicaManager(val config: KafkaConfig,
                      scheduler: Scheduler,
                      val logManager: LogManager,
                      val isShuttingDown: AtomicBoolean,
-                     threadNamePrefix: Option[String] = None) extends Logging with KafkaMetricsGroup {
+                     quotaManager: ReplicationQuotaManager,
+                     threadNamePrefix: Option[String] = None
+                    ) extends Logging with KafkaMetricsGroup {
   /* epoch of the controller that last changed the leader */
   @volatile var controllerEpoch: Int = KafkaController.InitialControllerEpoch - 1
   private val localBrokerId = config.brokerId
@@ -116,7 +119,7 @@ class ReplicaManager(val config: KafkaConfig,
     new Partition(t, p, time, this)
   })
   private val replicaStateChangeLock = new Object
-  val replicaFetcherManager = new ReplicaFetcherManager(config, this, metrics, jTime, threadNamePrefix)
+  val replicaFetcherManager = new ReplicaFetcherManager(config, this, metrics, jTime, threadNamePrefix, quotaManager)
   private val highWatermarkCheckPointThreadStarted = new AtomicBoolean(false)
   val highWatermarkCheckpoints = config.logDirs.map(dir => (new File(dir).getAbsolutePath, new OffsetCheckpoint(new File(dir, ReplicaManager.HighWatermarkFilename)))).toMap
   private var hwThreadInitialized = false
@@ -458,13 +461,14 @@ class ReplicaManager(val config: KafkaConfig,
                     replicaId: Int,
                     fetchMinBytes: Int,
                     fetchInfo: immutable.Map[TopicAndPartition, PartitionFetchInfo],
+                    quota: ReplicaQuota = UnboundedQuota,
                     responseCallback: Map[TopicAndPartition, FetchResponsePartitionData] => Unit) {
     val isFromFollower = replicaId >= 0
     val fetchOnlyFromLeader: Boolean = replicaId != Request.DebuggingConsumerId
     val fetchOnlyCommitted: Boolean = ! Request.isValidBrokerId(replicaId)
 
     // read from local logs
-    val logReadResults = readFromLocalLog(fetchOnlyFromLeader, fetchOnlyCommitted, fetchInfo)
+    val logReadResults = readFromLocalLog(fetchOnlyFromLeader, fetchOnlyCommitted, fetchInfo, quota)
 
     // if the fetch comes from the follower,
     // update its corresponding log end offset
@@ -489,8 +493,9 @@ class ReplicaManager(val config: KafkaConfig,
       val fetchPartitionStatus = logReadResults.map { case (topicAndPartition, result) =>
         (topicAndPartition, FetchPartitionStatus(result.info.fetchOffsetMetadata, fetchInfo.get(topicAndPartition).get))
       }
+
       val fetchMetadata = FetchMetadata(fetchMinBytes, fetchOnlyFromLeader, fetchOnlyCommitted, isFromFollower, fetchPartitionStatus)
-      val delayedFetch = new DelayedFetch(timeout, fetchMetadata, this, responseCallback)
+      val delayedFetch = new DelayedFetch(timeout, fetchMetadata, this, quota ,responseCallback)
 
       // create a list of (topic, partition) pairs to use as keys for this delayed fetch operation
       val delayedFetchKeys = fetchPartitionStatus.keys.map(new TopicPartitionOperationKey(_)).toSeq
@@ -507,8 +512,8 @@ class ReplicaManager(val config: KafkaConfig,
    */
   def readFromLocalLog(fetchOnlyFromLeader: Boolean,
                        readOnlyCommitted: Boolean,
-                       readPartitionInfo: Map[TopicAndPartition, PartitionFetchInfo]): Map[TopicAndPartition, LogReadResult] = {
-
+                       readPartitionInfo: Map[TopicAndPartition, PartitionFetchInfo],
+                       quota: ReplicaQuota): Map[TopicAndPartition, LogReadResult] = {
     readPartitionInfo.map { case (TopicAndPartition(topic, partition), PartitionFetchInfo(offset, fetchSize)) =>
       BrokerTopicStats.getBrokerTopicStats(topic).totalFetchRequestRate.mark()
       BrokerTopicStats.getBrokerAllTopicsStats().totalFetchRequestRate.mark()
@@ -536,10 +541,18 @@ class ReplicaManager(val config: KafkaConfig,
            * This can cause a replica to always be out of sync.
            */
           val initialLogEndOffset = localReplica.logEndOffset
+
           val logReadInfo = localReplica.log match {
             case Some(log) =>
               val adjustedFetchSize = if (Topic.isInternal(topic) && !readOnlyCommitted) Math.max(fetchSize, log.config.maxMessageSize) else fetchSize
-              log.read(offset, adjustedFetchSize, maxOffsetOpt)
+
+              //Try the read first, this tells us whether we need all of adjustedFetchSize for this partition
+              var fetch = log.read(offset, adjustedFetchSize, maxOffsetOpt)
+
+              //If the partition is marked as throttled, and we are over-quota then exclude it
+              if (quota.isThrottled(TopicAndPartition(topic, partition)) && quota.isQuotaExceeded)
+                fetch = FetchDataInfo(fetch.fetchOffsetMetadata, MessageSet.Empty)
+              fetch
             case None =>
               error("Leader for partition [%s,%d] does not have a local log".format(topic, partition))
               FetchDataInfo(LogOffsetMetadata.UnknownOffsetMetadata, MessageSet.Empty)

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/ReplicationQuotaManager.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/ReplicationQuotaManager.scala b/core/src/main/scala/kafka/server/ReplicationQuotaManager.scala
new file mode 100644
index 0000000..ba2fb92
--- /dev/null
+++ b/core/src/main/scala/kafka/server/ReplicationQuotaManager.scala
@@ -0,0 +1,202 @@
+/**
+  * 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.
+  */
+package kafka.server
+
+import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
+import kafka.common.TopicAndPartition
+import kafka.server.Constants._
+import kafka.server.ReplicationQuotaManagerConfig._
+import kafka.utils.CoreUtils._
+import kafka.utils.Logging
+import org.apache.kafka.common.metrics._
+import java.util.concurrent.locks.ReentrantReadWriteLock
+import org.apache.kafka.common.metrics.stats.SimpleRate
+import org.apache.kafka.common.utils.Time
+
+/**
+  * Configuration settings for quota management
+  *
+  * @param quotaBytesPerSecondDefault The default bytes per second quota allocated to internal replication
+  * @param numQuotaSamples            The number of samples to retain in memory
+  * @param quotaWindowSizeSeconds     The time span of each sample
+  *
+  */
+case class ReplicationQuotaManagerConfig(quotaBytesPerSecondDefault: Long = QuotaBytesPerSecondDefault,
+                                         numQuotaSamples: Int = DefaultNumQuotaSamples,
+                                         quotaWindowSizeSeconds: Int = DefaultQuotaWindowSizeSeconds)
+
+object ReplicationQuotaManagerConfig {
+  val QuotaBytesPerSecondDefault = Long.MaxValue
+  // Always have 10 whole windows + 1 current window
+  val DefaultNumQuotaSamples = 11
+  val DefaultQuotaWindowSizeSeconds = 1
+  // Purge sensors after 1 hour of inactivity
+  val InactiveSensorExpirationTimeSeconds = 3600
+}
+
+trait ReplicaQuota {
+  def isThrottled(topicAndPartition: TopicAndPartition): Boolean
+  def isQuotaExceeded(): Boolean
+}
+
+object Constants {
+  val AllReplicas = Seq[Int](-1)
+}
+
+/**
+  * Tracks replication metrics and comparing them to any quotas for throttled partitions.
+  *
+  * @param config          The quota configs
+  * @param metrics         The Metrics instance
+  * @param replicationType The name / key for this quota manager, typically leader or follower
+  * @param time            Time object to use
+  */
+class ReplicationQuotaManager(val config: ReplicationQuotaManagerConfig,
+                              private val metrics: Metrics,
+                              private val replicationType: QuotaType,
+                              private val time: Time) extends Logging with ReplicaQuota {
+  private val lock = new ReentrantReadWriteLock()
+  private val throttledPartitions = new ConcurrentHashMap[String, Seq[Int]]()
+  private var quota: Quota = null
+  private val sensorAccess = new SensorAccess
+  private val rateMetricName = metrics.metricName("byte-rate", replicationType.toString, s"Tracking byte-rate for ${replicationType}")
+
+  /**
+    * Update the quota
+    *
+    * @param quota
+    */
+  def updateQuota(quota: Quota) {
+    inWriteLock(lock) {
+      this.quota = quota
+      //The metric could be expired by another thread, so use a local variable and null check.
+      val metric = metrics.metrics.get(rateMetricName)
+      if (metric != null) {
+        metric.config(getQuotaMetricConfig(quota))
+      }
+    }
+  }
+
+  /**
+    * Check if the quota is currently exceeded
+    *
+    * @return
+    */
+  override def isQuotaExceeded(): Boolean = {
+    try {
+      sensor().checkQuotas()
+    } catch {
+      case qve: QuotaViolationException =>
+        trace("%s: Quota violated for sensor (%s), metric: (%s), metric-value: (%f), bound: (%f)".format(replicationType, sensor().name(), qve.metricName, qve.value, qve.bound))
+        return true
+    }
+    false
+  }
+
+  /**
+    * Is the passed partition throttled by this ReplicationQuotaManager
+    *
+    * @param topicPartition the partition to check
+    * @return
+    */
+  override def isThrottled(topicPartition: TopicAndPartition): Boolean = {
+    val partitions = throttledPartitions.get(topicPartition.topic)
+    if (partitions != null)
+      partitions.contains(topicPartition.partition) || (partitions eq AllReplicas)
+    else false
+  }
+
+  /**
+    * Add the passed value to the throttled rate. This method ignores the quota with
+    * the value being added to the rate even if the quota is exceeded
+    *
+    * @param value
+    */
+  def record(value: Long) {
+    try {
+      sensor().record(value)
+    } catch {
+      case qve: QuotaViolationException =>
+        trace(s"Record: Quota violated, but ignored, for sensor (${sensor.name}), metric: (${qve.metricName}), value : (${qve.value}), bound: (${qve.bound}), recordedValue ($value)")
+    }
+  }
+
+  /**
+    * Update the set of throttled partitions for this QuotaManager. The partitions passed, for
+    * any single topic, will replace any previous
+    *
+    * @param topic
+    * @param partitions the set of throttled partitions
+    * @return
+    */
+  def markThrottled(topic: String, partitions: Seq[Int]) {
+    throttledPartitions.put(topic, partitions)
+  }
+
+  /**
+    * Mark all replicas for this topic as throttled
+    *
+    * @param topic
+    * @return
+    */
+  def markThrottled(topic: String) {
+    markThrottled(topic, AllReplicas)
+  }
+
+  /**
+    * Remove list of throttled replicas for a certain topic
+    *
+    * @param topic
+    * @return
+    */
+  def removeThrottle(topic: String) {
+    throttledPartitions.remove(topic)
+  }
+
+  /**
+    * Returns the bound of the configured quota
+    *
+    * @return
+    */
+  def upperBound(): Long = {
+    inReadLock(lock) {
+      if (quota != null)
+        quota.bound().toLong
+      else
+        Long.MaxValue
+    }
+  }
+
+  private def getQuotaMetricConfig(quota: Quota): MetricConfig = {
+    new MetricConfig()
+      .timeWindow(config.quotaWindowSizeSeconds, TimeUnit.SECONDS)
+      .samples(config.numQuotaSamples)
+      .quota(quota)
+  }
+
+  private def sensor(): Sensor = {
+    sensorAccess.getOrCreate(
+      replicationType.toString,
+      InactiveSensorExpirationTimeSeconds,
+      lock,
+      metrics,
+      () => rateMetricName,
+      () => getQuotaMetricConfig(quota),
+      () => new SimpleRate()
+    )
+  }
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/server/SensorAccess.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/server/SensorAccess.scala b/core/src/main/scala/kafka/server/SensorAccess.scala
new file mode 100644
index 0000000..3a0130b
--- /dev/null
+++ b/core/src/main/scala/kafka/server/SensorAccess.scala
@@ -0,0 +1,76 @@
+/**
+  * 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.
+  */
+package kafka.server
+
+import java.util.concurrent.locks.ReentrantReadWriteLock
+
+import org.apache.kafka.common.MetricName
+import org.apache.kafka.common.metrics.{Metrics, Sensor, MeasurableStat, MetricConfig}
+
+/**
+  * Class which centralises the logic for creating/accessing sensors.
+  * The quota can be updated by wrapping it in the passed MetricConfig
+  *
+  * The later arguments are passed as methods as they are only called when the sensor is instantiated.
+  */
+class SensorAccess {
+
+  def getOrCreate(sensorName: String, expirationTime: Long, lock: ReentrantReadWriteLock, metrics: Metrics, metricName: () => MetricName, config: () => MetricConfig, measure: () => MeasurableStat): Sensor = {
+    var sensor: Sensor = null
+
+    /* Acquire the read lock to fetch the sensor. It is safe to call getSensor from multiple threads.
+     * The read lock allows a thread to create a sensor in isolation. The thread creating the sensor
+     * will acquire the write lock and prevent the sensors from being read while they are being created.
+     * It should be sufficient to simply check if the sensor is null without acquiring a read lock but the
+     * sensor being present doesn't mean that it is fully initialized i.e. all the Metrics may not have been added.
+     * This read lock waits until the writer thread has released its lock i.e. fully initialized the sensor
+     * at which point it is safe to read
+     */
+    lock.readLock().lock()
+    try {
+      sensor = metrics.getSensor(sensorName)
+    }
+    finally {
+      lock.readLock().unlock()
+    }
+
+    /* If the sensor is null, try to create it else return the existing sensor
+     * The sensor can be null, hence the null checks
+     */
+    if (sensor == null) {
+      /* Acquire a write lock because the sensor may not have been created and we only want one thread to create it.
+       * Note that multiple threads may acquire the write lock if they all see a null sensor initially
+       * In this case, the writer checks the sensor after acquiring the lock again.
+       * This is safe from Double Checked Locking because the references are read
+       * after acquiring read locks and hence they cannot see a partially published reference
+       */
+      lock.writeLock().lock()
+      try {
+        // Set the var for both sensors in case another thread has won the race to acquire the write lock. This will
+        // ensure that we initialise `ClientSensors` with non-null parameters.
+        sensor = metrics.getSensor(sensorName)
+        if (sensor == null) {
+          sensor = metrics.sensor(sensorName, config(), expirationTime)
+          sensor.add(metricName(), measure())
+        }
+      } finally {
+        lock.writeLock().unlock()
+      }
+    }
+    sensor
+  }
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/utils/CoreUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/utils/CoreUtils.scala b/core/src/main/scala/kafka/utils/CoreUtils.scala
index 21658d3..b4209e3 100755
--- a/core/src/main/scala/kafka/utils/CoreUtils.scala
+++ b/core/src/main/scala/kafka/utils/CoreUtils.scala
@@ -58,6 +58,7 @@ object CoreUtils extends Logging {
 
   /**
     * Create a thread
+    *
     * @param name The name of the thread
     * @param daemon Whether the thread should block JVM shutdown
     * @param fun The function to execute in the thread

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/main/scala/kafka/utils/Time.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/kafka/utils/Time.scala b/core/src/main/scala/kafka/utils/Time.scala
index f562ef7..d578a6a 100644
--- a/core/src/main/scala/kafka/utils/Time.scala
+++ b/core/src/main/scala/kafka/utils/Time.scala
@@ -40,7 +40,7 @@ object Time {
 /**
  * A mockable interface for time functions
  */
-trait Time {
+trait Time extends org.apache.kafka.common.utils.Time {
   
   def milliseconds: Long
 

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/integration/kafka/api/ClientQuotasTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/integration/kafka/api/ClientQuotasTest.scala b/core/src/test/scala/integration/kafka/api/ClientQuotasTest.scala
new file mode 100644
index 0000000..366507d
--- /dev/null
+++ b/core/src/test/scala/integration/kafka/api/ClientQuotasTest.scala
@@ -0,0 +1,206 @@
+/**
+ * Licensed 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.
+ **/
+
+package kafka.api
+
+import java.util.Properties
+
+import kafka.admin.AdminUtils
+import kafka.consumer.SimpleConsumer
+import kafka.integration.KafkaServerTestHarness
+import kafka.server._
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.{ConsumerConfig, KafkaConsumer}
+import org.apache.kafka.clients.producer._
+import org.apache.kafka.clients.producer.internals.ErrorLoggingCallback
+import org.apache.kafka.common.MetricName
+import org.apache.kafka.common.metrics.{Quota, KafkaMetric}
+import org.apache.kafka.common.protocol.ApiKeys
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.{After, Before, Test}
+import scala.collection.JavaConversions._
+import scala.collection.JavaConverters._
+
+import scala.collection.Map
+import scala.collection.mutable
+
+class ClientQuotasTest extends KafkaServerTestHarness {
+  private val producerBufferSize = 300000
+  private val producerId1 = "QuotasTestProducer-1"
+  private val producerId2 = "QuotasTestProducer-2"
+  private val consumerId1 = "QuotasTestConsumer-1"
+  private val consumerId2 = "QuotasTestConsumer-2"
+
+  val numServers = 2
+  val overridingProps = new Properties()
+
+  // Low enough quota that a producer sending a small payload in a tight loop should get throttled
+  overridingProps.put(KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp, "8000")
+  overridingProps.put(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp, "2500")
+
+  override def generateConfigs() = {
+    FixedPortTestUtils.createBrokerConfigs(numServers,
+                                           zkConnect,
+                                           enableControlledShutdown = false)
+            .map(KafkaConfig.fromProps(_, overridingProps))
+  }
+
+  var producers = mutable.Buffer[KafkaProducer[Array[Byte], Array[Byte]]]()
+  var consumers = mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]]()
+  var replicaConsumers = mutable.Buffer[SimpleConsumer]()
+
+  var leaderNode: KafkaServer = null
+  var followerNode: KafkaServer = null
+  private val topic1 = "topic-1"
+
+  @Before
+  override def setUp() {
+    super.setUp()
+    val producerProps = new Properties()
+    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
+    producerProps.put(ProducerConfig.ACKS_CONFIG, "0")
+    producerProps.put(ProducerConfig.BUFFER_MEMORY_CONFIG, producerBufferSize.toString)
+    producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, producerId1)
+    producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
+                      classOf[org.apache.kafka.common.serialization.ByteArraySerializer])
+    producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
+                      classOf[org.apache.kafka.common.serialization.ByteArraySerializer])
+    producers += new KafkaProducer[Array[Byte], Array[Byte]](producerProps)
+
+    producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, producerId2)
+    producers += new KafkaProducer[Array[Byte], Array[Byte]](producerProps)
+
+    val numPartitions = 1
+    val leaders = TestUtils.createTopic(zkUtils, topic1, numPartitions, numServers, servers)
+    leaderNode = if (leaders(0).get == servers.head.config.brokerId) servers.head else servers(1)
+    followerNode = if (leaders(0).get != servers.head.config.brokerId) servers.head else servers(1)
+    assertTrue("Leader of all partitions of the topic should exist", leaders.values.forall(leader => leader.isDefined))
+
+    // Create consumers
+    val consumerProps = new Properties
+    consumerProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "QuotasTest")
+    consumerProps.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 4096.toString)
+    consumerProps.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
+    consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
+    consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
+                      classOf[org.apache.kafka.common.serialization.ByteArrayDeserializer])
+    consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
+                      classOf[org.apache.kafka.common.serialization.ByteArrayDeserializer])
+
+    consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerId1)
+    consumers += new KafkaConsumer(consumerProps)
+    // Create replica consumers with the same clientId as the high level consumer. These requests should never be throttled
+    replicaConsumers += new SimpleConsumer("localhost", leaderNode.boundPort(), 1000000, 64*1024, consumerId1)
+
+    consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerId2)
+    consumers += new KafkaConsumer(consumerProps)
+    replicaConsumers += new SimpleConsumer("localhost", leaderNode.boundPort(), 1000000, 64*1024, consumerId2)
+  }
+
+  @After
+  override def tearDown() {
+    producers.foreach( _.close )
+    consumers.foreach( _.close )
+    replicaConsumers.foreach( _.close )
+    super.tearDown()
+  }
+
+  @Test
+  def testThrottledProducerConsumer() {
+    val allMetrics: mutable.Map[MetricName, KafkaMetric] = leaderNode.metrics.metrics().asScala
+
+    val numRecords = 1000
+    produce(producers.head, numRecords)
+
+    val producerMetricName = leaderNode.metrics.metricName("throttle-time",
+                                                           ApiKeys.PRODUCE.name,
+                                                           "Tracking throttle-time per client",
+                                                           "client-id", producerId1)
+    assertTrue("Should have been throttled", allMetrics(producerMetricName).value() > 0)
+
+    // Consumer should read in a bursty manner and get throttled immediately
+    consume(consumers.head, numRecords)
+    // The replica consumer should not be throttled also. Create a fetch request which will exceed the quota immediately
+    val request = new FetchRequestBuilder().addFetch(topic1, 0, 0, 1024*1024).replicaId(followerNode.config.brokerId).build()
+    replicaConsumers.head.fetch(request)
+    val consumerMetricName = leaderNode.metrics.metricName("throttle-time",
+                                                           ApiKeys.FETCH.name,
+                                                           "Tracking throttle-time per client",
+                                                           "client-id", consumerId1)
+    assertTrue("Should have been throttled", allMetrics(consumerMetricName).value() > 0)
+  }
+
+  @Test
+  def testProducerConsumerOverrideUnthrottled() {
+    // Give effectively unlimited quota for producerId2 and consumerId2
+    val props = new Properties()
+    props.put(ClientConfigOverride.ProducerOverride, Long.MaxValue.toString)
+    props.put(ClientConfigOverride.ConsumerOverride, Long.MaxValue.toString)
+
+    AdminUtils.changeClientIdConfig(zkUtils, producerId2, props)
+    AdminUtils.changeClientIdConfig(zkUtils, consumerId2, props)
+
+    TestUtils.retry(10000) {
+      val overrideProducerQuota = leaderNode.apis.quotas.produce.quota(producerId2)
+      val overrideConsumerQuota = leaderNode.apis.quotas.fetch.quota(consumerId2)
+
+      assertEquals(s"ClientId $producerId2 must have unlimited producer quota", Quota.upperBound(Long.MaxValue), overrideProducerQuota)
+      assertEquals(s"ClientId $consumerId2 must have unlimited consumer quota", Quota.upperBound(Long.MaxValue), overrideConsumerQuota)
+    }
+
+
+    val allMetrics: mutable.Map[MetricName, KafkaMetric] = leaderNode.metrics.metrics().asScala
+    val numRecords = 1000
+    produce(producers(1), numRecords)
+    val producerMetricName = leaderNode.metrics.metricName("throttle-time",
+                                                           ApiKeys.PRODUCE.name,
+                                                           "Tracking throttle-time per client",
+                                                           "client-id", producerId2)
+    assertEquals("Should not have been throttled", 0.0, allMetrics(producerMetricName).value(), 0.0)
+
+    // The "client" consumer does not get throttled.
+    consume(consumers(1), numRecords)
+    // The replica consumer should not be throttled also. Create a fetch request which will exceed the quota immediately
+    val request = new FetchRequestBuilder().addFetch(topic1, 0, 0, 1024*1024).replicaId(followerNode.config.brokerId).build()
+    replicaConsumers(1).fetch(request)
+    val consumerMetricName = leaderNode.metrics.metricName("throttle-time",
+                                                           ApiKeys.FETCH.name,
+                                                           "Tracking throttle-time per client",
+                                                           "client-id", consumerId2)
+    assertEquals("Should not have been throttled", 0.0, allMetrics(consumerMetricName).value(), 0.0)
+  }
+
+  def produce(p: KafkaProducer[Array[Byte], Array[Byte]], count: Int): Int = {
+    var numBytesProduced = 0
+    for (i <- 0 to count) {
+      val payload = i.toString.getBytes
+      numBytesProduced += payload.length
+      p.send(new ProducerRecord[Array[Byte], Array[Byte]](topic1, null, null, payload),
+             new ErrorLoggingCallback(topic1, null, null, true)).get()
+      Thread.sleep(1)
+    }
+    numBytesProduced
+  }
+
+  def consume(consumer: KafkaConsumer[Array[Byte], Array[Byte]], numRecords: Int) {
+    consumer.subscribe(List(topic1))
+    var numConsumed = 0
+    while (numConsumed < numRecords) {
+      for (cr <- consumer.poll(100)) {
+        numConsumed += 1
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/integration/kafka/api/QuotasTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/integration/kafka/api/QuotasTest.scala b/core/src/test/scala/integration/kafka/api/QuotasTest.scala
deleted file mode 100644
index b6a0ae5..0000000
--- a/core/src/test/scala/integration/kafka/api/QuotasTest.scala
+++ /dev/null
@@ -1,207 +0,0 @@
-/**
- * Licensed 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.
- **/
-
-package kafka.api
-
-import java.util.Properties
-
-import kafka.admin.AdminUtils
-import kafka.consumer.SimpleConsumer
-import kafka.integration.KafkaServerTestHarness
-import kafka.server.{ClientQuotaManager, ClientConfigOverride, KafkaConfig, KafkaServer}
-import kafka.utils.TestUtils
-import org.apache.kafka.clients.consumer.{ConsumerConfig, KafkaConsumer}
-import org.apache.kafka.clients.producer._
-import org.apache.kafka.clients.producer.internals.ErrorLoggingCallback
-import org.apache.kafka.common.MetricName
-import org.apache.kafka.common.metrics.{Quota, KafkaMetric}
-import org.apache.kafka.common.protocol.ApiKeys
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertTrue
-import org.junit.{After, Before, Test}
-import scala.collection.JavaConversions._
-import scala.collection.JavaConverters._
-
-import scala.collection.Map
-import scala.collection.mutable
-
-class QuotasTest extends KafkaServerTestHarness {
-  private val producerBufferSize = 300000
-  private val producerId1 = "QuotasTestProducer-1"
-  private val producerId2 = "QuotasTestProducer-2"
-  private val consumerId1 = "QuotasTestConsumer-1"
-  private val consumerId2 = "QuotasTestConsumer-2"
-
-  val numServers = 2
-  val overridingProps = new Properties()
-
-  // Low enough quota that a producer sending a small payload in a tight loop should get throttled
-  overridingProps.put(KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp, "8000")
-  overridingProps.put(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp, "2500")
-
-  override def generateConfigs() = {
-    FixedPortTestUtils.createBrokerConfigs(numServers,
-                                           zkConnect,
-                                           enableControlledShutdown = false)
-            .map(KafkaConfig.fromProps(_, overridingProps))
-  }
-
-  var producers = mutable.Buffer[KafkaProducer[Array[Byte], Array[Byte]]]()
-  var consumers = mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]]()
-  var replicaConsumers = mutable.Buffer[SimpleConsumer]()
-
-  var leaderNode: KafkaServer = null
-  var followerNode: KafkaServer = null
-  private val topic1 = "topic-1"
-
-  @Before
-  override def setUp() {
-    super.setUp()
-    val producerProps = new Properties()
-    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
-    producerProps.put(ProducerConfig.ACKS_CONFIG, "0")
-    producerProps.put(ProducerConfig.BUFFER_MEMORY_CONFIG, producerBufferSize.toString)
-    producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, producerId1)
-    producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
-                      classOf[org.apache.kafka.common.serialization.ByteArraySerializer])
-    producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
-                      classOf[org.apache.kafka.common.serialization.ByteArraySerializer])
-    producers += new KafkaProducer[Array[Byte], Array[Byte]](producerProps)
-
-    producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, producerId2)
-    producers += new KafkaProducer[Array[Byte], Array[Byte]](producerProps)
-
-    val numPartitions = 1
-    val leaders = TestUtils.createTopic(zkUtils, topic1, numPartitions, numServers, servers)
-    leaderNode = if (leaders(0).get == servers.head.config.brokerId) servers.head else servers(1)
-    followerNode = if (leaders(0).get != servers.head.config.brokerId) servers.head else servers(1)
-    assertTrue("Leader of all partitions of the topic should exist", leaders.values.forall(leader => leader.isDefined))
-
-    // Create consumers
-    val consumerProps = new Properties
-    consumerProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "QuotasTest")
-    consumerProps.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 4096.toString)
-    consumerProps.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
-    consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
-    consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
-                      classOf[org.apache.kafka.common.serialization.ByteArrayDeserializer])
-    consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
-                      classOf[org.apache.kafka.common.serialization.ByteArrayDeserializer])
-
-    consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerId1)
-    consumers += new KafkaConsumer(consumerProps)
-    // Create replica consumers with the same clientId as the high level consumer. These requests should never be throttled
-    replicaConsumers += new SimpleConsumer("localhost", leaderNode.boundPort(), 1000000, 64*1024, consumerId1)
-
-    consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, consumerId2)
-    consumers += new KafkaConsumer(consumerProps)
-    replicaConsumers += new SimpleConsumer("localhost", leaderNode.boundPort(), 1000000, 64*1024, consumerId2)
-  }
-
-  @After
-  override def tearDown() {
-    producers.foreach( _.close )
-    consumers.foreach( _.close )
-    replicaConsumers.foreach( _.close )
-    super.tearDown()
-  }
-
-  @Test
-  def testThrottledProducerConsumer() {
-    val allMetrics: mutable.Map[MetricName, KafkaMetric] = leaderNode.metrics.metrics().asScala
-
-    val numRecords = 1000
-    produce(producers.head, numRecords)
-
-    val producerMetricName = leaderNode.metrics.metricName("throttle-time",
-                                                           ApiKeys.PRODUCE.name,
-                                                           "Tracking throttle-time per client",
-                                                           "client-id", producerId1)
-    assertTrue("Should have been throttled", allMetrics(producerMetricName).value() > 0)
-
-    // Consumer should read in a bursty manner and get throttled immediately
-    consume(consumers.head, numRecords)
-    // The replica consumer should not be throttled also. Create a fetch request which will exceed the quota immediately
-    val request = new FetchRequestBuilder().addFetch(topic1, 0, 0, 1024*1024).replicaId(followerNode.config.brokerId).build()
-    replicaConsumers.head.fetch(request)
-    val consumerMetricName = leaderNode.metrics.metricName("throttle-time",
-                                                           ApiKeys.FETCH.name,
-                                                           "Tracking throttle-time per client",
-                                                           "client-id", consumerId1)
-    assertTrue("Should have been throttled", allMetrics(consumerMetricName).value() > 0)
-  }
-
-  @Test
-  def testProducerConsumerOverrideUnthrottled() {
-    // Give effectively unlimited quota for producerId2 and consumerId2
-    val props = new Properties()
-    props.put(ClientConfigOverride.ProducerOverride, Long.MaxValue.toString)
-    props.put(ClientConfigOverride.ConsumerOverride, Long.MaxValue.toString)
-
-    AdminUtils.changeClientIdConfig(zkUtils, producerId2, props)
-    AdminUtils.changeClientIdConfig(zkUtils, consumerId2, props)
-
-    TestUtils.retry(10000) {
-      val quotaManagers: Map[Short, ClientQuotaManager] = leaderNode.apis.quotaManagers
-      val overrideProducerQuota = quotaManagers.get(ApiKeys.PRODUCE.id).get.quota(producerId2)
-      val overrideConsumerQuota = quotaManagers.get(ApiKeys.FETCH.id).get.quota(consumerId2)
-
-      assertEquals(s"ClientId $producerId2 must have unlimited producer quota", Quota.upperBound(Long.MaxValue), overrideProducerQuota)
-      assertEquals(s"ClientId $consumerId2 must have unlimited consumer quota", Quota.upperBound(Long.MaxValue), overrideConsumerQuota)
-    }
-
-
-    val allMetrics: mutable.Map[MetricName, KafkaMetric] = leaderNode.metrics.metrics().asScala
-    val numRecords = 1000
-    produce(producers(1), numRecords)
-    val producerMetricName = leaderNode.metrics.metricName("throttle-time",
-                                                           ApiKeys.PRODUCE.name,
-                                                           "Tracking throttle-time per client",
-                                                           "client-id", producerId2)
-    assertEquals("Should not have been throttled", 0.0, allMetrics(producerMetricName).value(), 0.0)
-
-    // The "client" consumer does not get throttled.
-    consume(consumers(1), numRecords)
-    // The replica consumer should not be throttled also. Create a fetch request which will exceed the quota immediately
-    val request = new FetchRequestBuilder().addFetch(topic1, 0, 0, 1024*1024).replicaId(followerNode.config.brokerId).build()
-    replicaConsumers(1).fetch(request)
-    val consumerMetricName = leaderNode.metrics.metricName("throttle-time",
-                                                           ApiKeys.FETCH.name,
-                                                           "Tracking throttle-time per client",
-                                                           "client-id", consumerId2)
-    assertEquals("Should not have been throttled", 0.0, allMetrics(consumerMetricName).value(), 0.0)
-  }
-
-  def produce(p: KafkaProducer[Array[Byte], Array[Byte]], count: Int): Int = {
-    var numBytesProduced = 0
-    for (i <- 0 to count) {
-      val payload = i.toString.getBytes
-      numBytesProduced += payload.length
-      p.send(new ProducerRecord[Array[Byte], Array[Byte]](topic1, null, null, payload),
-             new ErrorLoggingCallback(topic1, null, null, true)).get()
-      Thread.sleep(1)
-    }
-    numBytesProduced
-  }
-
-  def consume(consumer: KafkaConsumer[Array[Byte], Array[Byte]], numRecords: Int) {
-    consumer.subscribe(List(topic1))
-    var numConsumed = 0
-    while (numConsumed < numRecords) {
-      for (cr <- consumer.poll(100)) {
-        numConsumed += 1
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/AdminTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/AdminTest.scala b/core/src/test/scala/unit/kafka/admin/AdminTest.scala
index 7cc25c8..5dca17f 100755
--- a/core/src/test/scala/unit/kafka/admin/AdminTest.scala
+++ b/core/src/test/scala/unit/kafka/admin/AdminTest.scala
@@ -16,9 +16,9 @@
  */
 package kafka.admin
 
+import kafka.server.KafkaConfig._
 import org.apache.kafka.common.errors.{InvalidReplicaAssignmentException, InvalidReplicationFactorException, InvalidTopicException, TopicExistsException}
 import org.apache.kafka.common.metrics.Quota
-import org.apache.kafka.common.protocol.ApiKeys
 import org.junit.Assert._
 import org.junit.Test
 import java.util.Properties
@@ -31,7 +31,7 @@ import kafka.common.TopicAndPartition
 import kafka.server.{ConfigType, KafkaConfig, KafkaServer}
 import java.io.File
 
-import TestUtils._
+import kafka.utils.TestUtils._
 
 import scala.collection.{Map, immutable}
 
@@ -278,7 +278,7 @@ class AdminTest extends ZooKeeperTestHarness with Logging with RackAwareTest {
     val partitionToBeReassigned = 0
     val topicAndPartition = TopicAndPartition(topic, partitionToBeReassigned)
     val reassignPartitionsCommand = new ReassignPartitionsCommand(zkUtils, Map(topicAndPartition -> newReplicas))
-    reassignPartitionsCommand.reassignPartitions
+    reassignPartitionsCommand.reassignPartitions()
     // create brokers
     val servers = TestUtils.createBrokerConfigs(2, zkConnect, false).map(b => TestUtils.createServer(KafkaConfig.fromProps(b)))
 
@@ -385,20 +385,23 @@ class AdminTest extends ZooKeeperTestHarness with Logging with RackAwareTest {
     val topic = "my-topic"
     val server = TestUtils.createServer(KafkaConfig.fromProps(TestUtils.createBrokerConfig(0, zkConnect)))
 
-    def makeConfig(messageSize: Int, retentionMs: Long) = {
-      var props = new Properties()
+    def makeConfig(messageSize: Int, retentionMs: Long, throttledReplicas: String) = {
+      val props = new Properties()
       props.setProperty(LogConfig.MaxMessageBytesProp, messageSize.toString)
       props.setProperty(LogConfig.RetentionMsProp, retentionMs.toString)
+      props.setProperty(LogConfig.ThrottledReplicasListProp, throttledReplicas)
       props
     }
 
-    def checkConfig(messageSize: Int, retentionMs: Long) {
+    def checkConfig(messageSize: Int, retentionMs: Long, throttledReplicas: String, quotaManagerIsThrottled: Boolean) {
       TestUtils.retry(10000) {
         for(part <- 0 until partitions) {
-          val logOpt = server.logManager.getLog(TopicAndPartition(topic, part))
-          assertTrue(logOpt.isDefined)
-          assertEquals(retentionMs, logOpt.get.config.retentionMs)
-          assertEquals(messageSize, logOpt.get.config.maxMessageSize)
+          val log = server.logManager.getLog(TopicAndPartition(topic, part))
+          assertTrue(log.isDefined)
+          assertEquals(retentionMs, log.get.config.retentionMs)
+          assertEquals(messageSize, log.get.config.maxMessageSize)
+          assertEquals(throttledReplicas, log.get.config.throttledReplicasList)
+          assertEquals(quotaManagerIsThrottled, server.quotaManagers.leader.isThrottled(new TopicAndPartition(topic, part)))
         }
       }
     }
@@ -406,24 +409,87 @@ class AdminTest extends ZooKeeperTestHarness with Logging with RackAwareTest {
     try {
       // create a topic with a few config overrides and check that they are applied
       val maxMessageSize = 1024
-      val retentionMs = 1000*1000
-      AdminUtils.createTopic(server.zkUtils, topic, partitions, 1, makeConfig(maxMessageSize, retentionMs))
-      checkConfig(maxMessageSize, retentionMs)
+      val retentionMs = 1000 * 1000
+      AdminUtils.createTopic(server.zkUtils, topic, partitions, 1, makeConfig(maxMessageSize, retentionMs, "0:0,1:0,2:0"))
+
+      //TODO - uncommenting this line reveals a bug. The quota manager is not updated when properties are added on topic creation.
+      //      checkConfig(maxMessageSize, retentionMs, "0:0,1:0,2:0", true)
 
       // now double the config values for the topic and check that it is applied
-      val newConfig: Properties = makeConfig(2*maxMessageSize, 2 * retentionMs)
-      AdminUtils.changeTopicConfig(server.zkUtils, topic, makeConfig(2*maxMessageSize, 2 * retentionMs))
-      checkConfig(2*maxMessageSize, 2 * retentionMs)
+      val newConfig: Properties = makeConfig(2 * maxMessageSize, 2 * retentionMs, "*")
+      AdminUtils.changeTopicConfig(server.zkUtils, topic, makeConfig(2 * maxMessageSize, 2 * retentionMs, "*"))
+      checkConfig(2 * maxMessageSize, 2 * retentionMs, "*", quotaManagerIsThrottled = true)
 
       // Verify that the same config can be read from ZK
       val configInZk = AdminUtils.fetchEntityConfig(server.zkUtils, ConfigType.Topic, topic)
       assertEquals(newConfig, configInZk)
+
+      //Now delete the config
+      AdminUtils.changeTopicConfig(server.zkUtils, topic, new Properties)
+      checkConfig(Defaults.MaxMessageSize, Defaults.RetentionMs, Defaults.ThrottledReplicasList,  quotaManagerIsThrottled = false)
+
+      //Add config back
+      AdminUtils.changeTopicConfig(server.zkUtils, topic, makeConfig(maxMessageSize, retentionMs, "0:0,1:0,2:0"))
+      checkConfig(maxMessageSize, retentionMs, "0:0,1:0,2:0", quotaManagerIsThrottled = true)
+
+      //Now ensure updating to "" removes the throttled replica list also
+      AdminUtils.changeTopicConfig(server.zkUtils, topic, new Properties(){put(LogConfig.ThrottledReplicasListProp, "")})
+      checkConfig(Defaults.MaxMessageSize, Defaults.RetentionMs, Defaults.ThrottledReplicasList,  quotaManagerIsThrottled = false)
+
     } finally {
       server.shutdown()
       CoreUtils.delete(server.config.logDirs)
     }
   }
 
+  @Test
+  def shouldPropagateDynamicBrokerConfigs() {
+    val brokerIds = Seq(0, 1, 2)
+    val servers = createBrokerConfigs(3, zkConnect).map(fromProps).map(TestUtils.createServer(_))
+
+    def wrap(limit: Long): Properties = {
+      val props = new Properties()
+      props.setProperty(KafkaConfig.ThrottledReplicationRateLimitProp, limit.toString)
+      props
+    }
+
+    def checkConfig(limit: Long) {
+      TestUtils.retry(10000) {
+        for (server <- servers) {
+          assertEquals("Leader Quota Manager was not updated", limit, server.quotaManagers.leader.upperBound)
+          assertEquals("Follower Quota Manager was not updated", limit, server.quotaManagers.follower.upperBound)
+        }
+      }
+    }
+
+    try {
+      val limit: Long = 42
+
+      // Set the limit & check it is applied to the log
+      AdminUtils.changeBrokerConfig(servers(0).zkUtils, brokerIds, wrap(limit))
+      checkConfig(limit)
+
+      // Now double the config values for the topic and check that it is applied
+      val newLimit = 2 * limit
+      AdminUtils.changeBrokerConfig(servers(0).zkUtils, brokerIds, wrap(newLimit))
+      checkConfig(newLimit)
+
+      // Verify that the same config can be read from ZK
+      for (brokerId <- brokerIds) {
+        val configInZk = AdminUtils.fetchEntityConfig(servers(brokerId).zkUtils, ConfigType.Broker, brokerId.toString)
+        assertEquals(newLimit, configInZk.getProperty(KafkaConfig.ThrottledReplicationRateLimitProp).toInt)
+      }
+
+      //Now delete the config
+      AdminUtils.changeBrokerConfig(servers(0).zkUtils, brokerIds, new Properties)
+      checkConfig(kafka.server.Defaults.ThrottledReplicationRateLimit)
+
+    } finally {
+      servers.foreach(_.shutdown())
+      servers.foreach(server => CoreUtils.delete(server.config.logDirs))
+    }
+  }
+
   /**
    * This test simulates a client config change in ZK whose notification has been purged.
    * Basically, it asserts that notifications are bootstrapped from ZK
@@ -447,8 +513,8 @@ class AdminTest extends ZooKeeperTestHarness with Logging with RackAwareTest {
     // Test that the existing clientId overrides are read
     val server = TestUtils.createServer(KafkaConfig.fromProps(TestUtils.createBrokerConfig(0, zkConnect)))
     try {
-      assertEquals(new Quota(1000, true), server.apis.quotaManagers(ApiKeys.PRODUCE.id).quota(clientId))
-      assertEquals(new Quota(2000, true), server.apis.quotaManagers(ApiKeys.FETCH.id).quota(clientId))
+      assertEquals(new Quota(1000, true), server.apis.quotas.produce.quota(clientId))
+      assertEquals(new Quota(2000, true), server.apis.quotas.fetch.quota(clientId))
     } finally {
       server.shutdown()
       CoreUtils.delete(server.config.logDirs)

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/ConfigCommandTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/ConfigCommandTest.scala b/core/src/test/scala/unit/kafka/admin/ConfigCommandTest.scala
index 7c71aed..be798ff 100644
--- a/core/src/test/scala/unit/kafka/admin/ConfigCommandTest.scala
+++ b/core/src/test/scala/unit/kafka/admin/ConfigCommandTest.scala
@@ -16,46 +16,63 @@
  */
 package kafka.admin
 
+import java.util.Properties
+
 import kafka.admin.ConfigCommand.ConfigCommandOptions
 import org.junit.Assert._
 import org.junit.Test
-import kafka.utils.Logging
+import kafka.utils.{ZkUtils, Logging}
 import kafka.zk.ZooKeeperTestHarness
 
 class ConfigCommandTest extends ZooKeeperTestHarness with Logging {
   @Test
-  def testArgumentParse() {
+  def shouldParseArgumentsForClientsEntityType() {
+    testArgumentParse("clients")
+  }
+
+  @Test
+  def shouldParseArgumentsForTopicsEntityType() {
+    testArgumentParse("topics")
+  }
+
+  @Test
+  def shouldParseArgumentsForBrokersEntityType() {
+    testArgumentParse("brokers")
+  }
+
+  def testArgumentParse(entityType: String) = {
     // Should parse correctly
     var createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
-                                                     "--entity-name", "x",
-                                                     "--entity-type", "clients",
-                                                     "--describe"))
+      "--entity-name", "x",
+      "--entity-type", entityType,
+      "--describe"))
     createOpts.checkArgs()
 
     // For --alter and added config
     createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
-                                                "--entity-name", "x",
-                                                "--entity-type", "clients",
-                                                "--alter",
-                                                "--add-config", "a=b,c=d"))
+      "--entity-name", "x",
+      "--entity-type", entityType,
+      "--alter",
+      "--add-config", "a=b,c=d"))
     createOpts.checkArgs()
 
     // For alter and deleted config
     createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
-                                                "--entity-name", "x",
-                                                "--entity-type", "clients",
-                                                "--alter",
-                                                "--delete-config", "a,b,c"))
+      "--entity-name", "x",
+      "--entity-type", entityType,
+      "--alter",
+      "--delete-config", "a,b,c"))
     createOpts.checkArgs()
 
     // For alter and both added, deleted config
     createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
-                                                "--entity-name", "x",
-                                                "--entity-type", "clients",
-                                                "--alter",
-                                                "--add-config", "a=b,c=d",
-                                                "--delete-config", "a"))
+      "--entity-name", "x",
+      "--entity-type", entityType,
+      "--alter",
+      "--add-config", "a=b,c=d",
+      "--delete-config", "a"))
     createOpts.checkArgs()
+
     val addedProps = ConfigCommand.parseConfigsToBeAdded(createOpts)
     assertEquals(2, addedProps.size())
     assertEquals("b", addedProps.getProperty("a"))
@@ -65,4 +82,139 @@ class ConfigCommandTest extends ZooKeeperTestHarness with Logging {
     assertEquals(1, deletedProps.size)
     assertEquals("a", deletedProps.head)
   }
+
+  @Test(expected = classOf[IllegalArgumentException])
+  def shouldFailIfUnrecognisedEntityType(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "client", "--entity-type", "not-recognised", "--alter", "--add-config", "a=b,c=d"))
+    ConfigCommand.alterConfig(null, createOpts, new TestAdminUtils)
+  }
+
+  @Test
+  def shouldAddClientConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "my-client-id",
+      "--entity-type", "clients",
+      "--alter",
+      "--add-config", "a=b,c=d"))
+
+    val configChange = new TestAdminUtils {
+      override def changeClientIdConfig(zkUtils: ZkUtils, clientId: String, configChange: Properties): Unit = {
+        assertEquals("my-client-id", clientId)
+        assertEquals("b", configChange.get("a"))
+        assertEquals("d", configChange.get("c"))
+      }
+    }
+    ConfigCommand.alterConfig(null, createOpts, configChange)
+  }
+
+  @Test
+  def shouldAddTopicConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "my-topic",
+      "--entity-type", "topics",
+      "--alter",
+      "--add-config", "a=b,c=d"))
+
+    val configChange = new TestAdminUtils {
+      override def changeTopicConfig(zkUtils: ZkUtils, topic: String, configChange: Properties): Unit = {
+        assertEquals("my-topic", topic)
+        assertEquals("b", configChange.get("a"))
+        assertEquals("d", configChange.get("c"))
+      }
+    }
+    ConfigCommand.alterConfig(null, createOpts, configChange)
+  }
+
+  @Test
+  def shouldAddBrokerConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "1",
+      "--entity-type", "brokers",
+      "--alter",
+      "--add-config", "a=b,c=d"))
+
+    val configChange = new TestAdminUtils {
+      override def changeBrokerConfig(zkUtils: ZkUtils, brokerIds: Seq[Int], configChange: Properties): Unit = {
+        assertEquals(Seq(1), brokerIds)
+        assertEquals("b", configChange.get("a"))
+        assertEquals("d", configChange.get("c"))
+      }
+    }
+    ConfigCommand.alterConfig(null, createOpts, configChange)
+  }
+
+  @Test
+  def shouldSupportCommaSeparatedValues(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "my-topic",
+      "--entity-type", "topics",
+      "--alter",
+      "--add-config", "a=b,c=[d,e ,f],g=[h,i]"))
+
+    val configChange = new TestAdminUtils {
+      override def changeBrokerConfig(zkUtils: ZkUtils, brokerIds: Seq[Int], configChange: Properties): Unit = {
+        assertEquals(Seq(1), brokerIds)
+        assertEquals("b", configChange.get("a"))
+        assertEquals("d,e ,f", configChange.get("c"))
+        assertEquals("h,i", configChange.get("g"))
+      }
+    }
+    ConfigCommand.alterConfig(null, createOpts, configChange)
+  }
+
+  @Test (expected = classOf[IllegalArgumentException])
+  def shouldNotUpdateBrokerConfigIfMalformedEntityName(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "1,2,3", //Don't support multiple brokers currently
+      "--entity-type", "brokers",
+      "--alter",
+      "--add-config", "a=b"))
+    ConfigCommand.alterConfig(null, createOpts, new TestAdminUtils)
+  }
+
+  @Test (expected = classOf[IllegalArgumentException])
+  def shouldNotUpdateBrokerConfigIfMalformedConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "1",
+      "--entity-type", "brokers",
+      "--alter",
+      "--add-config", "a="))
+    ConfigCommand.alterConfig(null, createOpts, new TestAdminUtils)
+  }
+
+  @Test (expected = classOf[IllegalArgumentException])
+  def shouldNotUpdateBrokerConfigIfMalformedBracketConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "1",
+      "--entity-type", "brokers",
+      "--alter",
+      "--add-config", "a=[b,c,d=e"))
+    ConfigCommand.alterConfig(null, createOpts, new TestAdminUtils)
+  }
+
+  @Test
+  def shouldDeleteBrokerConfig(): Unit = {
+    val createOpts = new ConfigCommandOptions(Array("--zookeeper", zkConnect,
+      "--entity-name", "1",
+      "--entity-type", "brokers",
+      "--alter",
+      "--delete-config", "a,c"))
+
+    val configChange = new TestAdminUtils {
+      override def fetchEntityConfig(zkUtils: ZkUtils, entityType: String, entityName: String): Properties = {
+        val properties: Properties = new Properties
+        properties.put("a", "b")
+        properties.put("c", "d")
+        properties.put("e", "f")
+        properties
+      }
+
+      override def changeBrokerConfig(zkUtils: ZkUtils, brokerIds: Seq[Int], configChange: Properties): Unit = {
+        assertEquals("f", configChange.get("e"))
+        assertEquals(1, configChange.size())
+      }
+    }
+    ConfigCommand.alterConfig(null, createOpts, configChange)
+  }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/ReassignPartitionsClusterTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/ReassignPartitionsClusterTest.scala b/core/src/test/scala/unit/kafka/admin/ReassignPartitionsClusterTest.scala
index 791c4d2..38fca87 100644
--- a/core/src/test/scala/unit/kafka/admin/ReassignPartitionsClusterTest.scala
+++ b/core/src/test/scala/unit/kafka/admin/ReassignPartitionsClusterTest.scala
@@ -10,17 +10,17 @@
   * 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.
   */
-package unit.kafka.admin
+package kafka.admin
 
-import kafka.admin.ReassignPartitionsCommand
+import kafka.common.TopicAndPartition
 import kafka.server.{KafkaConfig, KafkaServer}
 import kafka.utils.TestUtils._
 import kafka.utils.ZkUtils._
 import kafka.utils.{CoreUtils, Logging, ZkUtils}
 import kafka.zk.ZooKeeperTestHarness
+import org.junit.Assert.{assertEquals, assertTrue}
 import org.junit.{After, Before, Test}
-import org.junit.Assert.assertEquals
-
+import kafka.admin.ReplicationQuotaUtils._
 import scala.collection.Seq
 
 
@@ -41,8 +41,8 @@ class ReassignPartitionsClusterTest extends ZooKeeperTestHarness with Logging {
 
   @After
   override def tearDown() {
-    servers.foreach(_.shutdown())
-    servers.foreach(server => CoreUtils.delete(server.config.logDirs))
+    servers.par.foreach(_.shutdown())
+    servers.par.foreach(server => CoreUtils.delete(server.config.logDirs))
     super.tearDown()
   }
 
@@ -55,7 +55,7 @@ class ReassignPartitionsClusterTest extends ZooKeeperTestHarness with Logging {
 
     //When we move the replica on 100 to broker 101
     ReassignPartitionsCommand.executeAssignment(zkUtils, s"""{"version":1,"partitions":[{"topic":"$topicName","partition":0,"replicas":[101]}]}""")
-    waitForReasignmentToComplete()
+    waitForReassignmentToComplete()
 
     //Then the replica should be on 101
     assertEquals(zkUtils.getPartitionAssignmentForTopics(Seq(topicName)).get(topicName).get(partition), Seq(101))
@@ -75,7 +75,7 @@ class ReassignPartitionsClusterTest extends ZooKeeperTestHarness with Logging {
     //When rebalancing
     val newAssignment = ReassignPartitionsCommand.generateAssignment(zkUtils, brokers, json(topicName), true)._1
     ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment))
-    waitForReasignmentToComplete()
+    waitForReassignmentToComplete()
 
     //Then the replicas should span all three brokers
     val actual = zkUtils.getPartitionAssignmentForTopics(Seq(topicName))(topicName)
@@ -96,18 +96,146 @@ class ReassignPartitionsClusterTest extends ZooKeeperTestHarness with Logging {
     //When rebalancing
     val newAssignment = ReassignPartitionsCommand.generateAssignment(zkUtils, Array(100, 101), json(topicName), true)._1
     ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment))
-    waitForReasignmentToComplete()
+    waitForReassignmentToComplete()
 
     //Then replicas should only span the first two brokers
     val actual = zkUtils.getPartitionAssignmentForTopics(Seq(topicName))(topicName)
     assertEquals(actual.values.flatten.toSeq.distinct.sorted, Seq(100, 101))
   }
 
-  def waitForReasignmentToComplete() {
+  @Test
+  def shouldExecuteThrottledReassignment() {
+    //Given partitions on 3 of 3 brokers
+    val brokers = Array(100, 101, 102)
+    startBrokers(brokers)
+    createTopic(zkUtils, topicName, Map(
+      0 -> Seq(100, 101)
+    ), servers = servers)
+
+    //Given throttle set so replication will take a certain number of secs
+    val initialThrottle: Long = 1000 * 1000
+    val expectedDurationSecs = 5
+    val numMessages: Int = 50
+    val msgSize: Int = 100 * 1000
+    produceMessages(servers, topicName, numMessages, acks = 0, msgSize)
+    assertEquals(expectedDurationSecs, numMessages * msgSize / initialThrottle)
+
+    //Start rebalance which will move replica on 100 -> replica on 102
+    val newAssignment = ReassignPartitionsCommand.generateAssignment(zkUtils, Array(101, 102), json(topicName), true)._1
+
+    val start = System.currentTimeMillis()
+    ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment), initialThrottle)
+
+    //Check throttle config. Should be throttling replica 0 on 100 and 102 only.
+    checkThrottleConfigAddedToZK(initialThrottle, servers, topicName, "0:100,0:102")
+
+    //Await completion
+    waitForReassignmentToComplete()
+    val took = System.currentTimeMillis() - start
+
+    //Check move occurred
+    val actual = zkUtils.getPartitionAssignmentForTopics(Seq(topicName))(topicName)
+    assertEquals(actual.values.flatten.toSeq.distinct.sorted, Seq(101, 102))
+
+    //Then command should have taken longer than the throttle rate
+    assertTrue(s"Expected replication to be > ${expectedDurationSecs * 0.9 * 1000} but was $took", took > expectedDurationSecs * 0.9 * 1000)
+    assertTrue(s"Expected replication to be < ${expectedDurationSecs * 2 * 1000} but was $took", took < expectedDurationSecs * 2 * 1000)
+  }
+
+
+  @Test
+  def shouldOnlyThrottleMovingReplicas() {
+    //Given 6 brokers, two topics
+    val brokers = Array(100, 101, 102, 103, 104, 105)
+    startBrokers(brokers)
+    createTopic(zkUtils, "topic1", Map(
+      0 -> Seq(100, 101),
+      1 -> Seq(100, 101),
+      2 -> Seq(103, 104) //will leave in place
+    ), servers = servers)
+
+    createTopic(zkUtils, "topic2", Map(
+      0 -> Seq(104, 105),
+      1 -> Seq(104, 105),
+      2 -> Seq(103, 104)//will leave in place
+    ), servers = servers)
+
+    //Given throttle set so replication will take a while
+    val throttle: Long = 100 * 1000
+    produceMessages(servers, "topic1", 10, acks = 0, 100 * 1000)
+    produceMessages(servers, "topic2", 10, acks = 0, 100 * 1000)
+
+    //Start rebalance
+    val newAssignment = Map(
+      TopicAndPartition("topic1", 0) -> Seq(100, 102),//moved 101=>102
+      TopicAndPartition("topic1", 1) -> Seq(100, 102),//moved 101=>102
+      TopicAndPartition("topic2", 0) -> Seq(103, 105),//moved 104=>103
+      TopicAndPartition("topic2", 1) -> Seq(103, 105),//moved 104=>103
+      TopicAndPartition("topic1", 2) -> Seq(103, 104), //didn't move
+      TopicAndPartition("topic2", 2) -> Seq(103, 104)  //didn't move
+    )
+    ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment), throttle)
+
+    //Check throttle config. Should be throttling specific replicas for each topic.
+    checkThrottleConfigAddedToZK(throttle, servers, "topic1", "1:101,1:102,0:101,0:102")
+    checkThrottleConfigAddedToZK(throttle, servers, "topic2", "1:103,1:104,0:103,0:104")
+  }
+
+  @Test
+  def shouldChangeThrottleOnRerunAndRemoveOnVerify() {
+    //Given partitions on 3 of 3 brokers
+    val brokers = Array(100, 101, 102)
+    startBrokers(brokers)
+    createTopic(zkUtils, topicName, Map(
+      0 -> Seq(100, 101)
+    ), servers = servers)
+
+    //Given throttle set so replication will take at least 20 sec (we won't wait this long)
+    val initialThrottle: Long = 1000 * 1000
+    produceMessages(servers, topicName, numMessages = 200, acks = 0, valueBytes = 100 * 1000)
+
+    //Start rebalance
+    val newAssignment = ReassignPartitionsCommand.generateAssignment(zkUtils, Array(101, 102), json(topicName), true)._1
+
+    ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment), initialThrottle)
+
+    //Check throttle config
+    checkThrottleConfigAddedToZK(initialThrottle, servers, topicName, "0:100,0:102")
+
+    //Ensure that running Verify, whilst the command is executing, should have no effect
+    ReassignPartitionsCommand.verifyAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment))
+
+    //Check throttle config again
+    checkThrottleConfigAddedToZK(initialThrottle, servers, topicName, "0:100,0:102")
+
+    //Now re-run the same assignment with a larger throttle, which should only act to increase the throttle and make progress
+    val newThrottle = initialThrottle * 1000
+
+    ReassignPartitionsCommand.executeAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment), newThrottle)
+
+    //Check throttle was changed
+    checkThrottleConfigAddedToZK(newThrottle, servers, topicName, "0:100,0:102")
+
+    //Await completion
+    waitForReassignmentToComplete()
+
+    //Verify should remove the throttle
+    ReassignPartitionsCommand.verifyAssignment(zkUtils, ZkUtils.formatAsReassignmentJson(newAssignment))
+
+    //Check removed
+    checkThrottleConfigRemovedFromZK(topicName, servers)
+
+    //Check move occurred
+    val actual = zkUtils.getPartitionAssignmentForTopics(Seq(topicName))(topicName)
+    assertEquals(actual.values.flatten.toSeq.distinct.sorted, Seq(101, 102))
+  }
+
+  def waitForReassignmentToComplete() {
     waitUntilTrue(() => !zkUtils.pathExists(ReassignPartitionsPath), s"Znode ${ZkUtils.ReassignPartitionsPath} wasn't deleted")
   }
 
-  def json(topic: String): String = {
-    s"""{"topics": [{"topic": "$topic"}],"version":1}"""
+  def json(topic: String*): String = {
+    val topicStr = topic.map { t => "{\"topic\": \"" + t + "\"}" }.mkString(",")
+    s"""{"topics": [$topicStr],"version":1}"""
   }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/ReassignPartitionsCommandTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/ReassignPartitionsCommandTest.scala b/core/src/test/scala/unit/kafka/admin/ReassignPartitionsCommandTest.scala
index 0f71a19..91d5e20 100644
--- a/core/src/test/scala/unit/kafka/admin/ReassignPartitionsCommandTest.scala
+++ b/core/src/test/scala/unit/kafka/admin/ReassignPartitionsCommandTest.scala
@@ -16,9 +16,11 @@
  */
 package kafka.admin
 
+import kafka.common.TopicAndPartition
 import kafka.utils.{Logging, TestUtils}
 import kafka.zk.ZooKeeperTestHarness
 import org.junit.Test
+import org.junit.Assert.assertEquals
 
 class ReassignPartitionsCommandTest extends ZooKeeperTestHarness with Logging with RackAwareTest {
 
@@ -48,4 +50,90 @@ class ReassignPartitionsCommandTest extends ZooKeeperTestHarness with Logging wi
     checkReplicaDistribution(assignment, rackInfo, rackInfo.size, numPartitions, replicationFactor)
   }
 
+  @Test
+  def shouldFindMovingReplicas() {
+    val assigner = new ReassignPartitionsCommand(null, null)
+
+    //Given partition 0 moves from broker 100 -> 102
+    val existing = Map(TopicAndPartition("topic1",0) -> Seq(100, 101))
+    val proposed = Map(TopicAndPartition("topic1",0) -> Seq(101, 102))
+
+      //When
+    val moves = assigner.replicaMoves(existing, proposed)
+
+    //Then moving replicas should be throttled
+    assertEquals("0:100,0:102", moves.get("topic1").get)
+  }
+
+  @Test
+  def shouldFindMovingReplicasMultiplePartitions() {
+    val assigner = new ReassignPartitionsCommand(null, null)
+
+    //Given partitions 0 & 1 moves from broker 100 -> 102
+    val existing = Map(TopicAndPartition("topic1",0) -> Seq(100, 101), TopicAndPartition("topic1",1) -> Seq(100, 101))
+    val proposed = Map(TopicAndPartition("topic1",0) -> Seq(101, 102), TopicAndPartition("topic1",1) -> Seq(101, 102))
+
+      //When
+    val moves = assigner.replicaMoves(existing, proposed)
+
+    //Then moving replicas should be throttled
+    assertEquals("0:100,0:102,1:100,1:102", moves.get("topic1").get)
+  }
+
+  @Test
+  def shouldFindMovingReplicasMultipleTopics() {
+    val assigner = new ReassignPartitionsCommand(null, null)
+
+    //Given partition 0 on topics 1 & 2 move from broker 100 -> 102
+    val existing = Map(TopicAndPartition("topic1",0) -> Seq(100, 101), TopicAndPartition("topic2",0) -> Seq(100, 101))
+    val proposed = Map(TopicAndPartition("topic1",0) -> Seq(101, 102), TopicAndPartition("topic2",0) -> Seq(101, 102))
+
+    //When
+    val moves = assigner.replicaMoves(existing, proposed)
+
+    //Then moving replicas should be throttled
+    assertEquals("0:100,0:102", moves.get("topic1").get)
+    assertEquals("0:100,0:102", moves.get("topic2").get)
+  }
+
+  @Test
+  def shouldFindMovingReplicasMultipleTopicsAndPartitions() {
+    val assigner = new ReassignPartitionsCommand(null, null)
+
+    //Given
+    val existing = Map(
+      TopicAndPartition("topic1",0) -> Seq(100, 101),
+      TopicAndPartition("topic1",1) -> Seq(100, 101),
+      TopicAndPartition("topic2",0) -> Seq(100, 101),
+      TopicAndPartition("topic2",1) -> Seq(100, 101)
+    )
+    val proposed = Map(
+      TopicAndPartition("topic1",0) -> Seq(101, 102),
+      TopicAndPartition("topic1",1) -> Seq(101, 102),
+      TopicAndPartition("topic2",0) -> Seq(101, 102),
+      TopicAndPartition("topic2",1) -> Seq(101, 102)
+    )
+
+    //When
+    val moves = assigner.replicaMoves(existing, proposed)
+
+    //Then moving replicas should be throttled
+    assertEquals("0:100,0:102,1:100,1:102", moves.get("topic1").get)
+    assertEquals("0:100,0:102,1:100,1:102", moves.get("topic2").get)
+  }
+
+  @Test
+  def shouldFindTwoMovingReplicasInSamePartition() {
+    val assigner = new ReassignPartitionsCommand(null, null)
+
+    //Given partition 0 has 2 moves from broker 102 -> 104 & 103 -> 105
+    val existing = Map(TopicAndPartition("topic1",0) -> Seq(100, 101, 102, 103))
+    val proposed = Map(TopicAndPartition("topic1",0) -> Seq(100, 101, 104, 105))
+
+    //When
+    val moves = assigner.replicaMoves(existing, proposed)
+
+    //Then moving replicas should be throttled
+    assertEquals( "0:102,0:103,0:104,0:105", moves.get("topic1").get)
+  }
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/ReplicationQuotaUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/ReplicationQuotaUtils.scala b/core/src/test/scala/unit/kafka/admin/ReplicationQuotaUtils.scala
new file mode 100644
index 0000000..c6a42e2
--- /dev/null
+++ b/core/src/test/scala/unit/kafka/admin/ReplicationQuotaUtils.scala
@@ -0,0 +1,51 @@
+/**
+  * 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.
+  */
+package kafka.admin
+
+import kafka.log.LogConfig
+import kafka.server.{KafkaConfig, ConfigType, KafkaServer}
+import kafka.utils.TestUtils
+
+import scala.collection.Seq
+
+object ReplicationQuotaUtils {
+
+  def checkThrottleConfigRemovedFromZK(topic: String, servers: Seq[KafkaServer]): Boolean = {
+    TestUtils.waitUntilTrue(() => {
+      val brokerReset = servers.forall { server =>
+        val brokerConfig = AdminUtils.fetchEntityConfig(server.zkUtils, ConfigType.Broker, server.config.brokerId.toString)
+        !brokerConfig.contains(KafkaConfig.ThrottledReplicationRateLimitProp)
+      }
+      val topicConfig = AdminUtils.fetchEntityConfig(servers(0).zkUtils, ConfigType.Topic, topic)
+      val topicReset = !topicConfig.contains(LogConfig.ThrottledReplicasListProp)
+      brokerReset && topicReset
+    }, "Throttle limit/replicas was not unset")
+  }
+
+  def checkThrottleConfigAddedToZK(expectedThrottleRate: Long, servers: Seq[KafkaServer], topic: String, throttledReplicas: String): Boolean = {
+    TestUtils.waitUntilTrue(() => {
+      //Check for limit in ZK
+      val brokerConfigAvailable = servers.forall { server =>
+        val configInZk = AdminUtils.fetchEntityConfig(server.zkUtils, ConfigType.Broker, server.config.brokerId.toString)
+        val zkThrottleRate = configInZk.getProperty(KafkaConfig.ThrottledReplicationRateLimitProp)
+        zkThrottleRate != null && expectedThrottleRate == zkThrottleRate.toLong
+      }
+      //Check replicas assigned
+      val topicConfig = AdminUtils.fetchEntityConfig(servers(0).zkUtils, ConfigType.Topic, topic)
+      val property: String = topicConfig.getProperty(LogConfig.ThrottledReplicasListProp)
+      println(topic + "we found "+property)
+      val topicConfigAvailable = property == throttledReplicas
+      brokerConfigAvailable && topicConfigAvailable
+    }, "throttle limit/replicas was not set")
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/admin/TestAdminUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/admin/TestAdminUtils.scala b/core/src/test/scala/unit/kafka/admin/TestAdminUtils.scala
new file mode 100644
index 0000000..c7e101f
--- /dev/null
+++ b/core/src/test/scala/unit/kafka/admin/TestAdminUtils.scala
@@ -0,0 +1,27 @@
+/**
+  * 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.
+  */
+package kafka.admin
+
+import java.util.Properties
+import kafka.utils.ZkUtils
+
+class TestAdminUtils extends AdminUtilities {
+  override def changeBrokerConfig(zkUtils: ZkUtils, brokerIds: Seq[Int], configs: Properties): Unit = {}
+  override def fetchEntityConfig(zkUtils: ZkUtils, entityType: String, entityName: String): Properties = {new Properties}
+  override def changeClientIdConfig(zkUtils: ZkUtils, clientId: String, configs: Properties): Unit = {}
+  override def changeTopicConfig(zkUtils: ZkUtils, topic: String, configs: Properties): Unit = {}
+}

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/integration/FetcherTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/integration/FetcherTest.scala b/core/src/test/scala/unit/kafka/integration/FetcherTest.scala
index 3dd0454..881837f 100644
--- a/core/src/test/scala/unit/kafka/integration/FetcherTest.scala
+++ b/core/src/test/scala/unit/kafka/integration/FetcherTest.scala
@@ -90,5 +90,4 @@ class FetcherTest extends KafkaServerTestHarness {
         return
     }
   }
-
 }

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/log/LogConfigTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/log/LogConfigTest.scala b/core/src/test/scala/unit/kafka/log/LogConfigTest.scala
index 71e40da..3f2e3ed 100644
--- a/core/src/test/scala/unit/kafka/log/LogConfigTest.scala
+++ b/core/src/test/scala/unit/kafka/log/LogConfigTest.scala
@@ -19,8 +19,7 @@ package kafka.log
 
 import java.util.Properties
 
-import kafka.server.KafkaConfig
-import kafka.server.KafkaServer
+import kafka.server.{ThrottledReplicaValidator, KafkaConfig, KafkaServer}
 import kafka.utils.TestUtils
 import org.apache.kafka.common.config.ConfigException
 import org.junit.{Assert, Test}
@@ -65,6 +64,34 @@ class LogConfigTest {
     })
   }
 
+  @Test
+  def shouldValidateThrottledReplicasConfig() {
+    assertTrue(isValid("*"))
+    assertTrue(isValid("* "))
+    assertTrue(isValid(""))
+    assertTrue(isValid(" "))
+    assertTrue(isValid("100:10"))
+    assertTrue(isValid("100:10,12:10"))
+    assertTrue(isValid("100:10,12:10,15:1"))
+    assertTrue(isValid("100:10,12:10,15:1  "))
+
+    assertFalse(isValid("100"))
+    assertFalse(isValid("100:"))
+    assertFalse(isValid("100:0,"))
+    assertFalse(isValid("100:0,10"))
+    assertFalse(isValid("100:0,10:"))
+    assertFalse(isValid("100:0,10:   "))
+  }
+
+  private def isValid(configValue: String): Boolean = {
+    try {
+      ThrottledReplicaValidator.ensureValid("", configValue)
+    } catch {
+      case e: ConfigException => return false
+    }
+    true
+  }
+
   private def assertPropertyInvalid(name: String, values: AnyRef*) {
     values.foreach((value) => {
       val props = new Properties

http://git-wip-us.apache.org/repos/asf/kafka/blob/143a33bc/core/src/test/scala/unit/kafka/server/AbstractFetcherThreadTest.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/unit/kafka/server/AbstractFetcherThreadTest.scala b/core/src/test/scala/unit/kafka/server/AbstractFetcherThreadTest.scala
index b95f2bf..9edd3c0 100644
--- a/core/src/test/scala/unit/kafka/server/AbstractFetcherThreadTest.scala
+++ b/core/src/test/scala/unit/kafka/server/AbstractFetcherThreadTest.scala
@@ -28,6 +28,7 @@ import org.junit.Assert.{assertFalse, assertTrue}
 import org.junit.{Before, Test}
 
 import scala.collection.JavaConverters._
+import scala.collection.Map
 
 class AbstractFetcherThreadTest {