How would you implement a custom partitioner in Kafka, and why?
Instruction: Provide an example scenario where a custom partitioner is needed and explain how to implement one.
Updated
Official answer
Use the default key-based routing unless there is a concrete requirement it cannot meet. As an illustrative custom policy, reserve partition 0 for a stable category of customer keys beginning with priority_, and distribute other keys across the remaining partitions. This is placement, not a guarantee of priority scheduling; partition 0 can become a bottleneck.
The Java class below uses Kafka's Partitioner API. Save it as CategoryPartitioner.java, compile it with the Kafka client dependency, and place the compiled class on the producer classpath. It deliberately rejects missing/non-string keys and missing/empty configuration instead of silently routing them.
import java.util.Map;
import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.config.ConfigException;
public final class CategoryPartitioner implements Partitioner {
private String prefix;
@Override
public void configure(Map<String, ?> configs) {
Object configured = configs.get("category.prefix");
if (!(configured instanceof String)
|| ((String) configured).isEmpty()) {
throw new ConfigException("category.prefix must be nonempty");
}
prefix = (String) configured;
}
@Override
public int partition(String topic, Object key, byte[] keyBytes,
Object value, byte[] valueBytes, Cluster cluster) {
if (prefix == null) {
throw new IllegalStateException("Partitioner is not configured");
}
if (!(key instanceof String)) {
throw new IllegalArgumentException("A string key is required");
}
Integer count = cluster.partitionCountForTopic(topic);
if (count == null || count < 1) {
throw new IllegalArgumentException("Topic has no partitions");
}
String text = (String) key;
if (count == 1 || text.startsWith(prefix)) {
return 0;
}
return 1 + Math.floorMod(text.hashCode(), count - 1);
}
@Override
public void close() { }
}
Set partitioner.class=CategoryPartitioner and category.prefix=priority_, with a compatible string key serializer. Publish without an explicit partition so the partitioner is used. This example hashes the String key itself; it is not Kafka's default serialized-key hash algorithm.
floorMod handles negative hashes, including Integer.MIN_VALUE, and the one-partition branch avoids division by zero. All producers must use the same routing contract. Keep the category, key and partition count stable if per-entity ordering is required; changing a customer's category or adding partitions needs a coordinated migration. Do not choose a different partition merely because the intended leader is temporarily unavailable, since that would split the ordering domain.
Partitioner API, producer routing configuration, partition expansion