Partitioning Strategies & Custom Partitioners
Master key-hashing mechanics, understand how the Uniform Sticky Partitioner optimizes batching, and implement a custom Java partitioner.
How a producer decides which partition receives a message directly dictates system performance, consumer parallelism, and business ordering guarantees.
A poor partitioning strategy leads to hot partitions where one broker is saturated with 90% of traffic while neighboring brokers sit idle. An unkeyed strategy that uses legacy round-robin introduces severe network fragmentation.
In this lesson, you will master Kafka's built-in partitioning algorithms, understand the modern Sticky Partitioner, and build a custom Java partitioner to handle skewed workloads.
01The Three Built-In Routing Behaviors
When a producer sends a record, the default partitioner follows a three-level hierarchy:
1. Explicit Partition Assignment
If the ProducerRecord specifies a partition number directly, Kafka bypasses all hashing and appends the record strictly to that partition:
// Explicitly targeting Partition 2
ProducerRecord<String, String> record = new ProducerRecord<>(
"orders", 2, "cust-102", "{...}"
);Explicit assignment is rarely used in application code because it couples producer logic to cluster topology.
2. Hash-Based Partitioning (key != null)
If a key is present and no explicit partition is specified, Kafka hashes the serialized key bytes using the murmur2 algorithm:
partition = toPositive(murmur2(keyBytes)) % partitionCountBecause murmur2 is deterministic, all records with the same serialized key always route to the exact same partition, preserving strict chronological ordering for that business entity.
3. The Modern Uniform Sticky Partitioner (key == null)
Historically (prior to Kafka 2.4), unkeyed records were distributed using pure round-robin across partitions. This created a severe operational problem: every single message went to a different partition, resulting in dozens of tiny, half-empty 100-byte batches that exhausted buffer memory and crippled network throughput.
Starting with KIP-480, Kafka introduced the Uniform Sticky Partitioner:
- When records have no key (
key = null), the producer picks an active partition and sticks with it until the current batch fills up tobatch.size(16 KB) orlinger.mselapses. - Once that batch is dispatched to the broker, the producer selects the next partition and sticks to it for the next batch.
- This creates full, dense batches, reducing broker I/O requests and dramatically improving compression ratios while distributing records evenly across partitions over time.
Loading the rest of the lesson…