Apache Kafka® is an event streaming platform used by more than 30% of the Fortune 500 today. There are numerous features of Kafka that make it the de-facto standard for an event streaming platform, and in this blog post, I explain what I think are the top five things every Kafka developer should know.
Some items in our top five are performance related, while others are about the key architectural concepts that make Kafka tick. I hope that at the end of this blog post, you’ll walk away with a deeper understanding of how Kafka works, as well as with a new trick or two up your sleeve.
For data durability, the KafkaProducer has the configuration setting acks. The acks configuration specifies how many acknowledgments the producer receives to consider a record delivered to the broker. The options to choose from are:
As you can see, there is a trade-off to make here—and that’s by design because different applications have different requirements. You can opt for higher throughput with a chance for data loss, or you may prefer a very high data durability guarantee at the expense of a lower throughput.
Now let’s take a second to talk a little bit about the acks=all scenario. If you produce records with acks set to all to a cluster of three Kafka brokers, it means that under ideal conditions, Kafka contains three replicas of your data—one for the lead broker and one each for two followers. When the logs of each of these replicas all have the same record offsets, they are considered to be in sync. In other words, these in-sync replicas have the same content for a given topic partition. Take a look at the following illustration to clearly picture what’s going on:
But there’s some subtlety to using the acks=all configuration. What it doesn’t specify is how many replicas need to be in sync. The lead broker will always be in sync with itself. But you could have a situation where the two following brokers can’t keep up due to network partitions, record load, etc. So when a producer has a successful send, the actual number of acknowledgments could have come from only one broker! If the two followers are not in sync, the producer still receives the required number of acks, but it’s only the leader in this case.
For example:
By setting acks=all, you are placing a premium on the durability of your data. So if the replicas aren’t keeping up, it stands to reason that you want to raise an exception for new records until the replicas are caught up.
In a nutshell, having only one in-sync replica follows the “letter of the law” but not the “spirit of the law.” What we need is a guarantee when using the acks=all setting. A successful send involves at least a majority of the available in-sync brokers.
There just so happens to be one such configuration: min.insync.replicas. The min.insync.replicas configuration enforces the number of replicas that must be in sync for the write to proceed. Note that the min.insync.replicas configuration is set at the broker or topic level and is not a producer configuration. The default value for min.insync.replicas is one. So to avoid the scenario described above, in a three-broker cluster, you’d want to increase the value to two.
Let’s revisit our previous example from before and see the difference:
If the number of replicas that are in sync is below the configured amount, the lead broker won’t attempt to append the record to its log. The leader throws either a NotEnoughReplicasException or NotEnoughReplicasAfterAppendException, forcing the producer to retry the write. Having replicas out of sync with the leader is considered a retryable error, so the producer will continue to retry and send the records up to the configured delivery timeout.
So by setting the min.insync.replicas and producer acks configurations to work together in this way, you’ve increased the durability of your data.
Now let’s move on to the next items in our list: improvements to the Kafka clients. Over the past year, the Kafka producer and Kafka consumer APIs have added some new features that every Kafka developer should know.
Kafka uses partitions to increase throughput and spread the load of messages to all brokers in a cluster. Kafka records are in a key/value format, where the keys can be null. Kafka producers don’t immediately send records, instead placing them into partition-specific batches to be sent later. Batches are an effective means of increasing network utilization. There are three ways the partitioner determines into which partition the records should be written.
The partition can be explicitly provided in the ProducerRecord object via the overloaded ProducerRecord constructor. In this case, the producer always uses this partition.
If no partition is provided, and the ProducerRecord has a key, the producer takes the hash of the key modulo the number of partitions. The resulting number from that calculation is the partition that the producer will use.
If there is no key and no partition present in the ProducerRecord, then previously Kafka used a round robin approach to assign messages across partitions. The producer would assign the first record in the batch to partition zero, the second to partition one, and so on, until the end of the partitions. The producer would then start over with partition zero and repeat the entire process for all remaining records.
The following illustration depicts this process:
The round robin approach works well for even distribution of records across partitions. But there’s one drawback. Due to this “fair” round robin approach, you can end up sending multiple sparsely populated batches. It’s more efficient to send fewer batches with more records in each batch. Fewer batches mean less queuing of produce requests, hence less load on the brokers.
Let’s look at a simplified example where you have a topic with three partitions to explain this. For the sake of simplicity, let’s assume that your application produced nine records with no key, all arriving at the same time:
As you can see above, the nine incoming records will result in three batches of three records. But, it would be better if we could send one batch of nine records. As stated before, fewer batches result in less network traffic and less load on the brokers.
Apache Kafka 2.4.0 added the sticky partitioner approach, which now makes this possible. Instead of using a round robin approach per record, the sticky partitioner assigns records to the same partition until the batch is sent. Then, after sending a batch, the sticky partitioner increments the partition to use for the next batch. Let’s revisit our illustration from above but updated using the sticky partitioner:
By using the same partition until a batch is full or otherwise completed, we’ll send fewer produce requests, which reduces the load on the request queue and reduces latency of the system as well. It’s worth noting that the sticky partitioner still results in an even distribution of records. The even distribution occurs over time, as the partitioner sends a batch to each partition. You can think of it as a “per-batch” round robin or “eventually even” approach.
To learn more about the sticky partitioner, you can read the Apache Kafka Producer Improvements with the Sticky Partitioner blog post and the related KIP-480 design document.
Now let’s move on to the consumer changes.
Kafka is a distributed system, and one of the key things distributed systems need to do is deal with failures and disruptions—not just anticipate failures, but fully embrace them. A great example of how Kafka handles this expected disruption is the consumer group protocol, which manages multiple instances of a consumer for a single logical application. If an instance of a consumer stops, by design or otherwise, Kafka will rebalance and make sure another instance of the consumer takes over the work.
As of version 2.4, Kafka introduced a new rebalance protocol: cooperative rebalancing. But before we dive into the new protocol, let’s look in a bit more detail at the consumer group basics.
Let’s assume you have a distributed application with several consumers subscribed to a topic. Any set of consumers configured with the same group.id form one logical consumer called a consumer group. Each consumer in the group is responsible for consuming from one or more partitions of the subscribed topic(s). These partitions are assigned by the leader of the consumer group.
Here’s an illustration demonstrating this concept:
From the above illustration, you can see that under optimal conditions, all three consumers are processing records from two partitions each. But what happens if one of the applications suffers an error or can’t connect to the network anymore? Does processing for those topic partitions stop until you can restore the application in question? Fortunately, the answer is no, thanks to the consumer rebalancing protocol.
Here’s another illustration showing the consumer group protocol in action:
As you can see, Consumer 2 fails for some reason and either misses a poll or triggers a session timeout. The group coordinator removes it from the group and triggers what is known as a rebalance. A rebalance is a mechanism that attempts to evenly distribute (balance) the workload across all available members of a consumer group. In this case, since Consumer 2 left the group, the rebalance assigns its previously owned partitions to the other active members of the group. So as you can see, losing a consumer application for a particular group ID doesn’t result in a loss of processing on those topic partitions.
There is, however, a drawback of the default rebalancing approach. Each consumer gives up its entire assignment of topic partitions, and no processing takes place until the topic partitions are reassigned—sometimes referred to as a “stop-the-world” rebalance. To compound the issue, depending on the instance of the ConsumerPartitionAssignor used, consumers are simply reassigned the same topic partitions that they owned prior to the rebalance, the net effect being that there is no need to pause work on those partitions.
This implementation of the rebalance protocol is called eager rebalancing because it prioritizes the importance of ensuring that no consumers in the same group claim ownership over the same topic partitions. Ownership of the same topic partition by two consumers in the same group would result in undefined behavior.
While it is critical to keep any two consumers from claiming ownership over the same topic partition, it turns out that there is a better approach that provides safety without compromising on time spent not processing: incremental cooperative rebalancing. First introduced to Kafka Connect in Apache Kafka 2.3, this has now been implemented for the consumer group protocol too. With the cooperative approach, consumers don’t automatically give up ownership of all topic partitions at the start of the rebalance. Instead, all members encode their current assignment and forward the information to the group leader. The group leader then determines which partitions need to change ownership—instead of producing an entirely new assignment from scratch.
Now a second rebalance is issued, but this time, only the topic partitions that need to change ownership are involved. It could be revoking topic partitions that are no longer assigned or adding new topic partitions. For the topic partitions that are in both the new and old assignment, nothing has to change, which means continued processing for topic partitions that aren’t moving.
The bottom line is that eliminating the “stop-the-world” approach to rebalancing and only stopping the topic partitions involved means less costly rebalances, thus reducing the total time to complete the rebalance. Even long rebalances are less painful now that processing can continue throughout them. This positive change in rebalancing is made possible by using the CooperativeStickyAssignor. The CooperativeStickyAssignor makes the trade-off of having a second rebalance but with the benefit of a faster return to normal operations.
To enable this new rebalance protocol, you need to set the partition.assignment.strategy to use the new CooperativeStickyAssignor. Also, note that this change is entirely on the client side. To take advantage of the new rebalance protocol, you only need to update your client version. If you’re a Kafka Streams user, there is even better news. Kafka Streams enables the cooperative rebalance protocol by default, so there is nothing else to do.
The Apache Kafka binary installation includes several tools located in the bin directory. While you’ll find several tools in that directory, I want to show you the four tools that I think will have the most impact on your day-to-day work. I’m referring to the console-consumer, console-producer, dump-log, and delete-records.
The console producer allows you to produce records to a topic directly from the command line. Producing from the command line is a great way to quickly test new consumer applications when you aren’t producing data to the topics yet. To start the console producer, run this command:
kafka-console-producer --topic \
--broker-list <broker-host:port>
After you execute the command, there’s an empty prompt waiting for your input—just type in some characters and hit enter to produce a message.
Using the command line producer in this way does not send any keys, only values. Luckily, there is a way to send keys as well. You just have to update the command to include the necessary flags:
kafka-console-producer --topic \
--broker-list <broker-host:port> \
--property parse.key=true \
--property key.separator=":"
The choice of the key.separator property is arbitrary. You can use any character. And now, you can send full key/value pairs from the command line! If you are using Confluent Schema Registry, there are command line producers available to send records in Avro, Protobuf, and JSON Schema formats.
Now let’s take a look at the other side of the coin: consuming records from the command line.
The console consumer gives you the ability to consume records from a Kafka topic directly from the command line. Being able to quickly start a consumer can be an invaluable tool in prototyping or debugging. Consider building a new microservice. To quickly confirm that your producer application is sending messages, you can simply run this command:
kafka-console-consumer --topic \ --bootstrap-server <broker-host:port>
After you run this command, you’ll start seeing records scrolling across your screen (so long as data is currently being produced to the topic). If you want to see all the records from the start, you can add a --from-beginning flag to the command, and you’ll see all records produced to that topic.
kafka-console-consumer --topic <topic-name> \ --bootstrap-server <broker-host:port> \ --from-beginning
If you are using Schema Registry, there are command line consumers available for Avro, Protobuf, and JSON Schema encoded records. The Schema Registry command line consumers are intended for working with records in the Avro, Protobuf or JSON formats, while the plain consumers work with records of primitive Java types: String, Long, Double, Integer, etc. The default format expected for keys and values by the plain console consumer is the String type.
If the keys or values are not strings, you’ll need to p