🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Kafka Partitioning Strategies

Apache KafkaPartitioning⭐ Premium

Kafka Partitioning Strategies

Difficulty: Senior Level | Companies: LinkedIn, Uber, Netflix, Spotify, Confluent

What the partitioner is really deciding

Partitioning determines how messages are distributed across partitions in a Kafka topic. Understanding partitioning strategies is critical for designing systems with proper data locality and parallelism.

Why Partitioning Matters

Kafka gives you ordering only inside a single partition, so the partitioner decides which orderings your application can actually promise. If every event for one user lands in the same partition, a consumer can replay that user's history exactly as it happened; if those events are scattered, a single-threaded consumer sees them interleaved with everybody else's. Partitioning also sets the ceiling on parallelism: a topic with 12 partitions can have at most 12 consumers in one group doing useful work, no matter how many instances you deploy. Beyond those two effects, the partitioner controls the physical layout of data, because the controller spreads partition leaders across brokers when assignments are made. A key that hashes into a small subset of partitions produces hot spots where one broker takes most of the write traffic while the others idle, and that imbalance shows up in disk fill rate and request latency long before the cluster runs out of space.

Partition Assignment Diagram

Topic: user-events (4 partitions, replication factor 3)Producer (key: user_id=42)â–ŧPartitioner: hash(42) % 4 = 2â–ŧPartition 0 Partition 1 Partition 2 Partition 3┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐B1 (L) │ │ B2 (L) │ │ B3 (L) │ │ B4 (L)B2 (F) │ │ B3 (F) │ │ B4 (F) │ │ B1 (F)B3 (F) │ │ B4 (F) │ │ B1 (F) │ │ B2 (F)└─────────┘ └─────────┘ └─────────┘ └─────────┘

Default Partitioner Behavior

Kafka provides a default partitioner with specific behavior:

// Default partitioner logic (simplified)
public int partition(String topic, Object key, byte[] keyBytes, 
                     Object value, byte[] valueBytes, Cluster cluster) {
    List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
    int numPartitions = partitions.size();
    
    if (keyBytes != null) {
        // Key-based partitioning
        return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
    } else {
        // Round-robin for null keys
        return nextPartition(topic, null, numPartitions);
    }
}

â„šī¸

Key Insight: The default partitioner uses murmur2 hash algorithm (same as Java's String.hashCode()). This means the same key always goes to the same partition, but the distribution may not be perfectly uniform.

The default partitioner is DefaultPartitioner, and its behaviour changed in Kafka 2.4. Before 2.4 a null key was assigned round-robin across partitions, so every batch of unkeyed messages spread evenly but no two related records were ever guaranteed to meet. From 2.4 onward null keys use sticky partitioning: the producer fills one partition until the batch is full, then moves to another. Keys are unaffected, because Utils.toPositive(murmur2(keyBytes)) % numPartitions runs on every keyed record. Since murmur2 produces a 32-bit hash, distribution quality depends on the key itself. Integer keys, sequential ids and short timestamps spread reasonably well, but a constant such as ALL collapses the whole topic onto one partition. The modulo also means that expanding the partition count re-hashes most keys, so records for a given user can move to a different partition after an expansion.

Key-Based Partitioning

Most production systems use key-based partitioning for ordering guarantees:

// Java Producer with explicit key-based partitioning
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092,kafka2:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);

// Messages with same key go to same partition
ProducerRecord<String, String> record = new ProducerRecord<>(
    "user-events",
    "user-42",           // key
    "{\"action\": \"login\"}"  // value
);

producer.send(record, (metadata, exception) -> {
    System.out.println("Partition: " + metadata.partition());
    System.out.println("Offset: " + metadata.offset());
});

Python Producer Example

python
from kafka import KafkaProducer
import json

producer = KafkaProducer(
    bootstrap_servers=['kafka1:9092', 'kafka2:9092'],
    key_serializer=lambda k: k.encode('utf-8'),
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)

# Key-based partitioning
for event in user_events:
    producer.send(
        topic='user-events',
        key=event['user_id'],  # Ensures same user goes to same partition
        value=event
    )

producer.flush()

Custom Partitioner Implementation

When you need control over partition assignment:

// Custom partitioner for geographic routing
public class GeoPartitioner implements Partitioner {
    private Map<String, Integer> geoPartitions;
    
    @Override
    public void configure(Map<String, ?> configs) {
        geoPartitions = new HashMap<>();
        geoPartitions.put("US", 0);
        geoPartitions.put("EU", 1);
        geoPartitions.put("ASIA", 2);
        // Default partition for unknown regions
        geoPartitions.put("DEFAULT", 3);
    }
    
    @Override
    public int partition(String topic, Object key, byte[] keyBytes,
                         Object value, byte[] valueBytes, Cluster cluster) {
        String region = extractRegion(value.toString());
        int partition = geoPartitions.getOrDefault(region, 
                        geoPartitions.get("DEFAULT"));
        
        // Ensure partition is within range
        int numPartitions = cluster.partitionsForTopic(topic).size();
        return partition % numPartitions;
    }
    
    @Override
    public void close() {}
    
    @Override
    public void onNewBatch(String topic, TopicPartition partition, int batchRoleId) {}
}

Configuration

props.put("partitioner.class", "com.example.GeoPartitioner");
# producer.config
bootstrap.servers=kafka1:9092,kafka2:9092
partitioner.class=com.example.GeoPartitioner

Sticky Partitioning (Kafka 2.4+)

Sticky partitioning reduces batch latency by sending to the same partition until it fills:

// Sticky partitioning is the default in Kafka 2.4+
props.put("partitioner.class", 
          "org.apache.kafka.clients.producer.internals.DefaultPartitioner");

// Behavior:
// 1. First message with null key goes to partition 0
// 2. Subsequent messages go to partition 0 until batch is full
// 3. Then moves to next partition
// 4. Reduces metadata requests and improves throughput

When to Use Sticky

Sticky partitioning trades a little ordering flexibility for much larger batches. Use it when messages carry no key, because with no key there is no ordering requirement to protect and throughput is the only thing that matters. It also helps with bursts: instead of spreading a burst across every partition in small batches, the producer concentrates it, reaches batch_size sooner, and pays the per-request overhead fewer times. Do not rely on it when records must be grouped, because the group boundary is decided by batch fill rather than by anything in the data. A rule you can state in an interview: keyed traffic is hashed, unkeyed traffic is sticky, and any grouping that comes from the business belongs in an explicit custom partitioner.

Round-Robin Partitioning

For uniform distribution when ordering doesn't matter:

// Custom round-robin partitioner
public class RoundRobinPartitioner implements Partitioner {
    private AtomicInteger counter = new AtomicInteger(0);
    
    @Override
    public int partition(String topic, Object key, byte[] keyBytes,
                         Object value, byte[] valueBytes, Cluster cluster) {
        int numPartitions = cluster.partitionsForTopic(topic).size();
        return counter.getAndIncrement() % numPartitions;
    }
    
    @Override
    public void configure(Map<String, ?> configs) {}
    
    @Override
    public void close() {}
    
    @Override
    public void onNewBatch(String topic, TopicPartition partition, int batchRoleId) {}
}

Custom Partitioner in Python

python
from kafka.partitioner.base import Partitioner
from kafka.partitioner import murmur2

class GeoPartitioner(Partitioner):
    def partition(self, key, num_partitions):
        """Custom partition logic for geographic routing"""
        if key is None:
            return 0
            
        region = self.extract_region(key)
        region_map = {
            'US': 0,
            'EU': 1,
            'ASIA': 2
        }
        
        partition = region_map.get(region, num_partitions - 1)
        return partition % num_partitions
    
    def extract_region(self, key):
        """Extract region from key or value"""
        # Your custom logic here
        return 'US'

# Usage
producer = KafkaProducer(
    bootstrap_servers=['kafka1:9092'],
    partitioner=GeoPartitioner
)

Choosing keys that survive growth

A good key has three properties: it is stable for the life of the entity, it is cheap to compute, and it spreads evenly under modulo. Stability matters most, because the moment a key changes meaning the entity's history splits across partitions and every per-key ordering guarantee quietly breaks. Entity ids such as user:42 or order:9931 satisfy this; a composite key like user:42:2024-06-01 does not, since it changes daily and scatters one user across many partitions. Evenness is harder than it looks, because keys that share a long common prefix, such as tenant-0000000001 through tenant-0000000009, can cluster after hashing even though they look distinct to a human. If you spot clustering, either salt the key with a short random suffix and accept that per-key ordering is gone, or route on an explicit field with a custom partitioner. Verify the result with kafka-topics.sh --describe and compare log end offsets across partitions: a spread wider than roughly 20 percent between the busiest and the quietest partition deserves investigation.

Matching partition count to consumers

Partition count is a capacity decision rather than a storage decision. The working rule is to size partitions from throughput: measure the bytes per second you must ingest, divide by the sustained single-partition rate your disks and network can hold (commonly 10 to 30 MB/s on modest hardware), and round up. Then check the opposite direction, because consumers cannot exceed partitions. A group with 16 consumers and 8 partitions leaves 8 of them idle, while a group with 4 consumers and 32 partitions forces each consumer to track 8 partitions at once, which raises per-consumer lag and lengthens every rebalance. There is also a fixed cost carried by each partition: index files, file descriptors, replica fetch requests and controller bookkeeping, so thousands of mostly idle partitions slow the controller and stretch rebalance time. Adding partitions later is easy for producers but disruptive for consumers, since re-hashing moves keys and any state keyed by partition has to be rebuilt.

Partitioning Best Practices

The practices below come down to one idea: decide where data should live before producing it, rather than discovering afterwards where the default hash put it. Work in order, because each step depends on the one before it. Pick the key from the ordering guarantee you actually need, verify that the hash spreads it across partitions, choose a partition count from measured throughput and consumer count, then watch the distribution continuously, because skew grows gradually as traffic changes and is rarely visible in a single sample.

1. Key Design

// Good: Deterministic, well-distributed keys
String key = "user:" + userId;           // Clear prefix
String key = "order:" + orderId;          // Unique identifier

// Bad: Keys that cause skew
String key = "ALL";                        // All messages to one partition
String key = timestamp.toString();        // May create hotspots

2. Monitoring Partition Distribution

# Check partition distribution
kafka-topics.sh --describe --topic user-events --bootstrap-server kafka1:9092

# Output shows offset ranges per partition
Topic: user-events	TopicId: abc123	PartitionCount: 4	ReplicationFactor: 3
	Partition: 0	Leader: 1	Replicas: 1,2,3	Isr: 1,2,3
	Partition: 1	Leader: 2	Replicas: 2,3,1	Isr: 2,3,1
	Partition: 2	Leader: 3	Replicas: 3,1,2	Isr: 3,1,2
	Partition: 3	Leader: 1	Replicas: 1,2,3	Isr: 1,2,3

3. Avoiding Hot Partitions

python
# Monitor partition metrics
from kafka import KafkaConsumer
from prometheus_client import Gauge

consumer = KafkaConsumer(
    'user-events',
    bootstrap_servers=['kafka1:9092'],
    group_id='monitoring-group'
)

partition_offsets = Gauge('kafka_partition_offset', 
                          'Current offset per partition', 
                          ['partition'])

for message in consumer:
    partition_offsets.labels(
        partition=message.partition
    ).set(message.offset)

Follow-Up Questions

Interviewers usually move from mechanics to a design question: given this traffic pattern, which key and which partition count would you choose, and how would you prove the choice was right? Answer with a measurement rather than a preference, and mention how you would re-check the distribution after a partition expansion, since that is the moment ordering guarantees are most likely to break.

  1. How does the default partitioner handle messages with null keys versus non-null keys?
  2. What are the trade-offs between key-based partitioning and round-robin partitioning?
  3. When would you implement a custom partitioner instead of using the default?
  4. How can you detect and handle partition skew in a production Kafka cluster?
  5. Explain how sticky partitioning improves performance compared to round-robin.

Common Mistakes

Using a timestamp or an always-changing value as the message key

Fix: Key on a stable entity id such as user or order so one entity's records stay in one partition and ordering holds

Adding partitions to relieve a hot topic without checking key distribution

Fix: Expansion re-hashes almost every key; confirm the busiest to quietest partition spread first, then rebuild any partition-keyed state

Deploying more consumers than the topic has partitions

Fix: Size partitions from throughput first, then cap consumer instances at the partition count so no instance sits idle

Key Takeaways

  • Ordering is only guaranteed inside one partition, so the partitioner decides which orderings your consumers can rely on
  • The default partitioner hashes non-null keys with murmur2 modulo partition count, and uses sticky assignment for null keys since Kafka 2.4
  • Partition count bounds consumer parallelism and carries a fixed per-partition cost, so it should be derived from measured throughput
  • Partition skew is measurable: describe the topic and compare log end offsets to catch a hot partition before it becomes an outage
🔒

Premium Content

Kafka Partitioning Strategies

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement