Producers, keys and partitioning

Mid-level Always asked 7 min

On this page

The question

How does a Kafka producer choose the partition for a record?

30-second answer

If the record names a partition, it goes there. Otherwise, with a key, the default partitioner hashes the serialized key with murmur2 and takes it modulo the partition count, so the same key always lands in the same partition. Without a key, the producer sticks to one partition until the batch is full or sent, then switches, favoring less loaded brokers. A custom Partitioner can replace the rule.

Understand it

Which partition gets the record?

Explore

customer-42 hashes to 1604496153. Modulo 3, that is P0, for every event with this key, so they stay in order.

3
View as text

A producer sends three events of one order, created, paid and shipped, to a topic drawn as one row per partition. The row that receives them is highlighted, with the hash and the modulo written above.

customer-42 hashes to 1604496153. Modulo 3, that is P0, for every event with this key, so they stay in order.

customer-7 hashes to 863653111. Modulo 3, that is P1, for every event with this key, so they stay in order.

With 4 partitions, customer-42 hashes to P1, not P0. Old events stay in P0, so a consumer may read new ones first.

customer-12 hashes to 1390874690. Modulo 4, that is P2, for every event with this key, so they stay in order.

No key: the producer fills a batch for one partition, then moves to another. The events of one order spread out, and nothing keeps them in order.

A producer sends three events of one order, created, paid and shipped, to a topic drawn as one row per partition. The row that receives them is highlighted, with the hash and the modulo written above.

customer-42 hashes to 1604496153. Modulo 3, that is P0, for every event with this key, so they stay in order.

customer-7 hashes to 863653111. Modulo 3, that is P1, for every event with this key, so they stay in order.

With 4 partitions, customer-42 hashes to P1, not P0. Old events stay in P0, so a consumer may read new ones first.

customer-12 hashes to 1390874690. Modulo 4, that is P2, for every event with this key, so they stay in order.

No key: the producer fills a batch for one partition, then moves to another. The events of one order spread out, and nothing keeps them in order.

Takeaway: The default partitioner hashes the key with murmur2 and takes it modulo the partition count, so one key always lands in one partition and stays in order. Change the count, and keys move.

acks levels when the leader crashes

Compare

The producer does not wait for any answer. The leader crashed before writing r4, and nobody can tell: fastest, and the producer cannot even retry.

View as text

A producer sends record r4 to the leader of a partition, broker 1. Brokers 2 and 3 are followers. Each broker shows its copy of the log, records r1 to r4. Broker 1 then crashes and broker 2 becomes the new leader.

acks=0: The producer does not wait for any answer. The leader crashed before writing r4, and nobody can tell: fastest, and the producer cannot even retry. r4 lost, and the producer never knew.

acks=1: The leader writes r4 and acknowledges at once, then crashes before the followers copy it. Broker 2 becomes leader without r4: acknowledged, and still lost. r4 lost after an ack.

acks=all: The leader acknowledges only once all in-sync replicas hold r4. The crash comes after, so broker 2 takes over with r4. Slower, and nothing acknowledged is lost. r4 kept: the new leader has it.

A producer sends record r4 to the leader of a partition, broker 1. Brokers 2 and 3 are followers. Each broker shows its copy of the log, records r1 to r4. Broker 1 then crashes and broker 2 becomes the new leader.

acks=0: The producer does not wait for any answer. The leader crashed before writing r4, and nobody can tell: fastest, and the producer cannot even retry. r4 lost, and the producer never knew.

acks=1: The leader writes r4 and acknowledges at once, then crashes before the followers copy it. Broker 2 becomes leader without r4: acknowledged, and still lost. r4 lost after an ack.

acks=all: The leader acknowledges only once all in-sync replicas hold r4. The crash comes after, so broker 2 takes over with r4. Slower, and nothing acknowledged is lost. r4 kept: the new leader has it.

Takeaway: acks decides when the producer hears "written". Only acks=all waits for the followers, so only acks=all survives losing the leader right after the ack. It is the default since Kafka 3.0.

How the producer picks a partitionIf the record names a partition, it goes there. Otherwise, if it has a key, the default partitioner takes the murmur2 hash of the key modulo the partition count. Without a key, the producer sticks to one partition until the current batch is sent, then picks another, favoring less loaded brokers.yesnoyesnoRecord to sendPartition seton the record?That partitionKey set?murmur2 of the key,mod partition countSticky: the currentbatch's partition
How the producer picks a partitionIf the record names a partition, it goes there. Otherwise, if it has a key, the default partitioner takes the murmur2 hash of the key modulo the partition count. Without a key, the producer sticks to one partition until the current batch is sent, then picks another, favoring less loaded brokers.yesnoyesnoRecord to sendPartition seton the record?That partitionKey set?murmur2 of the key,mod partition countSticky: the currentbatch's partition
How the producer picks a partition

In code

@Service
class OrderEvents {
    private static final Logger log = LoggerFactory.getLogger(OrderEvents.class);
    private final KafkaTemplate<String, OrderEvent> kafka;

    OrderEvents(KafkaTemplate<String, OrderEvent> kafka) { this.kafka = kafka; }

    void publish(OrderEvent e) {
        kafka.send("orders", e.orderId(), e)              // key: all events of an order, one partition
            .whenComplete((result, ex) -> {
                if (ex != null) log.error("not written after retries: {}", e, ex);
                else log.debug("partition {}, offset {}",
                    result.getRecordMetadata().partition(), result.getRecordMetadata().offset());
            });                                           // send is asynchronous: this runs later
    }
}
Send with a key, and find out whether the broker took it
spring.kafka.producer.acks=all
spring.kafka.producer.properties.enable.idempotence=true
# Retries continue until this deadline, then the send fails
spring.kafka.producer.properties.delivery.timeout.ms=120000
# Wait up to 10 ms to fill bigger batches, and compress them
spring.kafka.producer.properties.linger.ms=10
spring.kafka.producer.batch-size=65536
spring.kafka.producer.compression-type=zstd
# Topic side: replication factor 3 and min.insync.replicas=2
A producer that loses nothing and writes no retry duplicates
// No key: created, paid and shipped can land in three partitions and be consumed in any order
 Wrong kafka.send("orders", event);

// The order ID as key: one partition, so consumers see the events in the order they were sent
 Right kafka.send("orders", event.orderId(), event);
Events of one order sent without a key can be read out of order
An idempotent producer retries without writing twiceThe producer sends a batch with producer ID 9 and sequence 5. The leader appends it, but the acknowledgement is lost. The producer retries the same batch with the same sequence. The leader sees it already has sequence 5 from producer 9, does not append it again, and acknowledges.Partition leaderProducer, ID 9already have 5 from ID 9: not appended againbatch, sequence 5ack lost on the networkretry: batch, sequence 5ack, written once
An idempotent producer retries without writing twiceThe producer sends a batch with producer ID 9 and sequence 5. The leader appends it, but the acknowledgement is lost. The producer retries the same batch with the same sequence. The leader sees it already has sequence 5 from producer 9, does not append it again, and acknowledges.Partition leaderProducer, ID 9already have 5 from ID 9: not appended againbatch, sequence 5ack lost on the networkretry: batch, sequence 5ack, written once
An idempotent producer retries without writing twice

Solve it

Shipping sometimes sees “order paid” before “order created”

Orders publishes OrderCreated, OrderPaid and OrderShipped to the topic orders, which has 6 partitions. The records have no key. Shipping, with 3 consumers in one group, now and then rejects a payment for an order it has not seen yet. Find the cause and fix it, without giving up parallel consumption.

  1. Locate the ordering guarantee. Kafka orders records within a partition only. With no key, the producer spreads batches over all 6 partitions, so the three events of one order can sit in different partitions, read by different consumers at different speeds.
  2. Key by the entity that needs order. Use the order ID as the key: every event of one order goes to the same partition, while different orders still spread over all 6, so parallelism stays.
  3. Keep retries from reordering. A failed batch retried behind a newer one could swap them; the idempotent producer prevents that with up to 5 requests in flight. It is the default since Kafka 3.0, so make sure nobody turned it off.
  4. Keep the consumer sequential per partition. Do not hand records of one partition to a thread pool without grouping them by key, or the consumer reorders them itself.
  5. Check. In a test, send the three events for one order and assert they report the same partition, and that the consumer receives them in order.
@Test
void eventsOfOneOrderShareAPartition() throws Exception {
    String orderId = "order-7";
    var created = kafka.send("orders", orderId, new OrderCreated(orderId)).get();
    var paid = kafka.send("orders", orderId, new OrderPaid(orderId)).get();
    var shipped = kafka.send("orders", orderId, new OrderShipped(orderId)).get();

    int p = created.getRecordMetadata().partition();
    assertThat(paid.getRecordMetadata().partition()).isEqualTo(p);
    assertThat(shipped.getRecordMetadata().partition()).isEqualTo(p);
    assertThat(paid.getRecordMetadata().offset()).isGreaterThan(created.getRecordMetadata().offset());
}
Key by order ID, and check the three events share a partition

How to answer

  • Same key, same partition, which is what keeps the events of one entity in order.
  • Adding partitions changes the modulo, so existing keys move to other partitions.
  • A key with far more traffic than the others makes one partition hot.
  • Unkeyed records are spread for throughput, with no ordering between them.

Common mistakes

  • Saying unkeyed records go round-robin, one by one. Since Kafka 2.4 the producer fills a batch for one partition, then switches.
  • Expecting a key to keep its partition after partitions are added.

Follow-up questions

How do you keep the order of events in Kafka?

Kafka guarantees order only within a partition, so give every event that must stay in order the same key, such as the order ID. Keep the idempotent producer on, so retries cannot swap batches. On the consumer side, a partition is read by one consumer of the group; process its records sequentially, or in parallel only across different keys. Order across different keys is not guaranteed, and usually not needed.

  • Ordering is per key, through the partition, not per topic.
  • Retries without idempotence and with several requests in flight can reorder records.
  • A single partition keeps total order, but caps the group at one consumer.

See it in the infographic: Which partition gets the record?

What do acks=0, acks=1 and acks=all mean for a producer?

acks sets when the leader answers a write. With 0, the producer does not wait, so it never learns of a failure. With 1, the leader answers after writing to its own log; if it crashes before the followers copy the record, the record is lost although acknowledged. With all, the leader answers once every in-sync replica has it, which survives a leader crash. all is the default since Kafka 3.0.

  • acks=all waits for in-sync replicas, not for every replica.
  • min.insync.replicas, often 2, sets how many in-sync replicas acks=all needs, or the write fails.
  • Higher acks costs latency, not much throughput, thanks to batching.

See it in the infographic: acks levels when the leader crashes

What is an idempotent producer?

A producer whose retries cannot create duplicates or reorder records. The broker gives it a producer ID, and the producer numbers every batch per partition. If a retry arrives with a sequence number the leader already wrote, the leader acknowledges it without writing it again. It needs acks=all and at most 5 requests in flight, and it is on by default since Kafka 3.0.

  • It removes duplicates caused by retries, within one producer session and partition.
  • It does not stop your code from calling send twice for the same event.
  • Exactly-once across partitions and with consumers needs transactions on top.

See it in the infographic: acks levels when the leader crashes

How do linger.ms and batch.size affect a producer?

The producer groups records per partition into batches. batch.size, 16 KB by default, caps a batch; linger.ms is how long the producer waits for more records before sending a batch that is not full. A few milliseconds of linger gives bigger batches, better compression and far fewer requests, for a small latency cost. Kafka 4.0 raised the linger.ms default from 0 to 5 ms for that reason.

  • Throughput comes from batching and compression, such as lz4 or zstd.
  • Batches are per partition, so many partitions with little traffic each make small batches.
  • buffer.memory caps what waits to be sent; when full, send blocks.

See it in the infographic: Which partition gets the record?

Is KafkaProducer.send synchronous? How do you know a record was written?

No. send adds the record to a batch in memory and returns a Future at once; a background thread sends batches and retries. You learn the result from the callback, or by calling get, which blocks and kills throughput if done for every record. If retries run out within delivery.timeout.ms, two minutes by default, the future fails, and the application must log, alert or store the record.

  • Spring's KafkaTemplate.send returns a CompletableFuture in Spring Kafka 3.
  • Unhandled failures are silent data loss.
  • close and flush wait for batches still in memory.

See it in the infographic: acks levels when the leader crashes

What is a hot partition, and how do you deal with it?

One partition gets much more traffic than the others, because one key is very busy, such as a big customer, so its consumer falls behind while others idle. Options are a finer key, such as customer and order, or salting the key with a suffix, which gives up strict order for that key. Measure per-partition lag and bytes in before changing keys.

Can you change the partition count of a live topic safely?

You can only increase it, and existing records stay where they are. New records of a key may go to another partition, so a consumer can read them before older ones still waiting in the old partition. For ordered topics, plan enough partitions up front, or move to a new topic and migrate.

Check yourself

1. Records with key customer-42 go to partition 0 of a topic with 3 partitions. The topic grows to 4 partitions. Where do new customer-42 records go?
Show answers
  • Wherever the hash modulo 4 points, which may be another partition: Correct. The partitioner takes the hash modulo the current count, so the key can move.
  • Still partition 0, because Kafka remembers each key: Incorrect. Kafka keeps no key-to-partition table; it recomputes every time.
  • Spread over all 4 partitions: Incorrect. A key always maps to one partition for a given count.
2. With acks=1, the leader acknowledges a record and crashes before any follower copies it. A follower becomes leader. What happens to the record?
Show answers
  • It is lost, although the producer got an ack: Correct. Only the old leader had it, and the new leader never did.
  • It is kept, because it was acknowledged: Incorrect. The ack only meant the old leader wrote it.
  • The producer notices and sends it again: Incorrect. The producer got its ack, so it has nothing to retry.
3. What does the idempotent producer prevent?
Show answers
  • A retried batch being written twice to a partition: Correct. The leader drops a batch whose sequence number it already wrote.
  • A consumer processing a record twice: Incorrect. That is on the consumer side, and needs idempotent processing or transactions.
  • The application calling send twice with the same event: Incorrect. Two send calls are two records with two sequence numbers.