Apache Kafka & Stream Processing Fundamentals · Aula

Chaves de mensagens e estratégias de particionamento

Aprenda como o Kafka usa chaves de mensagens para encaminhar registros às partições, como isso garante a ordenação e como projetar chaves e particionadores personalizados.

Aula 4 de 413 etapas

Chaves de mensagens e estratégias de particionamento é uma aula grátis de Apache Kafka & Stream Processing Fundamentals no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Apache Kafka & Stream Processing Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Apache Kafka & Stream Processing Fundamentals inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

The Role of the Key

Every Kafka record can carry an optional key. The key is not just data — it determines which partition the record is written to.

Default Partitioner

When a key is present, the default partitioner hashes it and maps the hash to a partition. The same key always lands in the same partition (for a fixed partition count).

partition = hash(key) % numPartitions

No Key Behavior

If you send records without a key, the producer distributes them across partitions (sticky batching in modern clients) for balanced load — but ordering across partitions is not guaranteed.

Ordering Guarantee

Kafka guarantees ordering only within a partition. By keying related records (e.g. all events for one order id), you guarantee they are processed in order.

send("orders", orderId, event);  // all events for an order stay ordered

Choosing a Good Key

A good key reflects your ordering and grouping needs.

  • User events keyed by userId.
  • Order events keyed by orderId.
  • Avoid keys with too few distinct values (causes hot partitions).

Hot Partitions

If one key value dominates traffic, its partition becomes a hotspot while others sit idle. Watch key cardinality and distribution to keep load balanced.

Keying in Spring Boot

Pass the key as the second argument to send; Spring forwards it to the partitioner.

kafkaTemplate.send("orders", order.getId(), payload);

Custom Partitioner

For special routing logic, implement the Partitioner interface and override partition().

public int partition(String topic, Object key, byte[] keyBytes,
        Object value, byte[] valueBytes, Cluster cluster) {
    return isVip(key) ? 0 : 1 + (Math.abs(key.hashCode()) % (n - 1));
}

Registering the Partitioner

Tell the producer to use your class via configuration.

spring:
  kafka:
    producer:
      properties:
        partitioner.class: com.example.VipPartitioner

Partition Count and Keys

Changing the partition count changes hash % numPartitions, so existing keys may move to new partitions, breaking ordering. Choose partition count carefully up front.

Putting It Together

Keys are the link between data and partitions. They give you per-key ordering, drive load distribution, and can be customized with a partitioner for advanced routing.

Quick Check

Test your understanding of keys and partitioning.

Recap

You learned message keys and partitioning.

  • The key determines the target partition via hashing.
  • Same key, same partition, ordered processing.
  • Low-cardinality keys cause hot partitions.
  • A custom Partitioner enables advanced routing.
Grátis para começar

Aprenda Apache Kafka & Stream Processing Fundamentals com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Chaves de mensagens e estratégias de particionamento” é grátis?

Sim — o texto completo de “Chaves de mensagens e estratégias de particionamento” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Apache Kafka & Stream Processing Fundamentals, atualize para CoddyKit PRO. O curso de Apache Kafka & Stream Processing Fundamentals inclui 4 aulas no total.

O que vou aprender em “Chaves de mensagens e estratégias de particionamento”?

Aprenda como o Kafka usa chaves de mensagens para encaminhar registros às partições, como isso garante a ordenação e como projetar chaves e particionadores personalizados. Você pratica Apache Kafka & Stream Processing Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Apache Kafka & Stream Processing Fundamentals?

Nenhuma experiência prévia é necessária. Apache Kafka & Stream Processing Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Chaves de mensagens e estratégias de particionamento”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Apache Kafka & Stream Processing Fundamentals?

Sim. Cada aula de Apache Kafka & Stream Processing Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Produzindo mensagens no Kafka
  2. Consumindo mensagens do Kafka
  3. Entendendo partições e deslocamentos
  4. Chaves de mensagens e estratégias de particionamento
← Voltar para Apache Kafka & Stream Processing Fundamentals