What Are Partitioning Keys in Kafka?

What Are Partitioning Keys in Kafka?

A beginner-friendly guide to the small piece of every Kafka event that decides where it lives, whether it stays in order, and how evenly your whole system shares its work.

Imagine a large post office that sorts millions of letters every day. Each letter carries a postcode. The sorters never read the letter itself. They look only at the postcode and drop the letter into the sack for that area. All letters for the same postcode end up in the same sack, in the order they arrived, and each sack goes to one delivery van. Because of the postcode, related letters travel together, and the workload is shared among many vans. In Apache Kafka, the partitioning key is that postcode. It is a tiny label on every event, yet it quietly controls order, balance, and scale. This guide explains how keys work and how to choose them wisely.

1A Quick Refresher: Topics and Partitions

To understand keys, we first need to remember what they choose between.

Topics are split into partitions

Apache Kafka stores streams of events, such as orders, payments, clicks, or sensor readings. Events are grouped into named categories called topics. To make a topic big and fast, Kafka splits it into several smaller logs called partitions. Each partition is an ordered, append-only list of events, and different partitions can live on different servers, called brokers.

Someone must choose the partition

When an application sends an event, Kafka must decide which partition receives it. If this choice were random every time, related events would be scattered, and their order would be lost. If the choice were always the same partition, the whole system would be limited by a single log. The partitioning key is the tool that lets the sender guide this choice in a smart, predictable way.

Simple Analogy

A supermarket has twelve checkout counters. A friendly manager could send every customer to a random counter, or use a rule such as “customers whose surname starts with the same letter go to the same counter”. The rule keeps related people together. The partitioning key is that rule’s input.

i
Helpful Note

Kafka only promises order inside a single partition. Keys are the practical way to make sure the events that need to stay in order all land in the same partition.

2What Is a Partitioning Key?

A partitioning key is an optional piece of data attached to an event that Kafka uses to decide which partition stores it.

The simple definition

Every Kafka event, often called a record, has a key and a value. The value is the main content, such as the details of an order. The key is a short identity, such as a customer number, an order number, or a device name. When the key is present, the producer feeds it into a fixed calculation, and the result points to one specific partition. The same key always gives the same answer, as long as the number of partitions stays the same.

Parts of a record

Part 1

Key

The identity used to pick the partition and to group related events together.

Part 2

Value

The actual content of the event, such as the items in an order.

Part 3

Headers

Optional labels travelling with the event, such as its source or a tracking number.

Part 4

Timestamp

The time attached to the event.

Simple Analogy

Think of a parcel. The postcode on the label is the key, because it decides which van takes the parcel. The contents of the box are the value. Stickers such as “fragile” are the headers, and the date stamp is the timestamp.

!
Common Mistake

Thinking the key must be unique for each event. It should not be. A key is meant to be shared by all events that belong together, such as all events of one customer. A unique key for every event would scatter events and defeat its purpose.

3How a Key Becomes a Partition

The trick is a fixed calculation that turns any key into a partition number.

The three small steps

1

Convert the key to bytes

Kafka stores raw bytes, so a serializer first turns the key into bytes in an agreed format.

2

Calculate a hash

A hash function scrambles the bytes into a large number. The same bytes always produce the same number, and different keys usually produce very different numbers.

3

Fit the number to the partitions

The large number is divided by the count of partitions, and the remainder becomes the partition number. With six partitions, the answer is always a number from zero to five.

flowchart LR
  K["Key: customer 4711"] --> SR["Serialize to bytes"]
  SR --> H["Hash into a large number"]
  H --> M["Divide by partition count and take the remainder"]
  M --> P["Partition 3"]
        
FIG 1 — From key to partition in three steps

Why hashing works well

A good hash function spreads different keys roughly evenly across all partitions. If you have thousands of different customers, each partition receives roughly the same number of them. The calculation is also extremely fast, needs no lookup table, and does not require any coordination between producers. Any producer, anywhere, running the same rule, sends the same customer to the same partition.

Simple Analogy

Imagine dealing a pack of playing cards into six piles by adding up the digits of each card’s serial number and taking the remainder after dividing by six. Cards with the same serial number always land in the same pile, and with many different cards, the piles stay roughly equal in size.

i
Helpful Note

The hash is not about secrecy. It is only a fair way of dividing keys among partitions. Anyone who knows the key and the partition count can work out the partition.

4The Big Promise: Order per Key

The reason keys matter most is that they give you ordering exactly where you need it.

Order lives inside one partition

Kafka stores and delivers events of a single partition in the exact order they were written. Across different partitions, there is no promised order, because partitions are read independently and at different speeds. So if two events must be read in order, they must be in the same partition, and the key is how you make that happen.

An example with a bank account

A customer deposits money, then withdraws money, then closes the account. If these three events used no key, they might land in three different partitions and be read in any order, and the bank might try to withdraw from an account that has not yet been credited. With the account number as key, all three events share a partition and are read in the order they were sent.

sequenceDiagram
  participant P as Producer
  participant P1 as Partition 1
  participant P2 as Partition 2
  P->>P1: Account A - Deposit
  P->>P2: Account B - Deposit
  P->>P1: Account A - Withdraw
  P->>P1: Account A - Close
  P->>P2: Account B - Withdraw
  Note over P1: Account A events stay in order
  Note over P2: Account B events stay in order
        
FIG 2 — Each account’s events share one partition and keep their order
Simple Analogy

In a bank with several counters, each customer’s file is always handled by the same clerk. That clerk works through the papers of one customer in the order they arrived, while other clerks serve other customers at the same time. The file never gets shuffled.

Order is preserved for one key

All events for account A appear in the sequence they were sent, no matter how busy other partitions are.

Order is not promised between keys

An event for account B may be read before or after an event for account A, and that is usually perfectly fine.

!
Common Mistake

Expecting a strict global order across a whole topic. If you truly need every event ordered against every other, you would need a single partition, giving up the speed and scale that partitions bring.

5What Happens Without a Key?

A key is optional. Sending without one is a perfectly good choice in many situations.

The keyless approach

When an event has no key, also called a null key, the producer has no identity to follow, so it simply spreads events across partitions to keep the load balanced. Older clients used to rotate one event at a time. Modern clients use a smarter approach called sticky partitioning: they fill a batch for one partition, send it, and then switch to another partition. This keeps batches large, which is much more efficient than scattering single events.

When to skip the key

If the order of events does not matter and no consumer needs related events together, a null key gives the most even balance and the simplest scaling. Click streams, log lines, and general metrics are common examples.

SituationUse a Key?Reason
Account or order history that must stay in orderYesSame key keeps events in one partition and in sequence
Counting or joining events by identityYesRelated events must meet in the same place
Keeping only the latest state per itemYesCompaction works on keys
General logs with no ordering needNoEven spread and larger batches
Independent click eventsUsually noNo relationship between events
Simple Analogy

A restaurant assigns regular customers to the same waiter every visit so the waiter remembers their preferences. Random walk-in customers are simply given to whichever waiter is free. Keyed events are the regulars, and keyless events are the walk-ins.

6Choosing a Good Key

Picking the key is one of the most important design decisions in a Kafka system. A few simple questions guide it.

Question 1

What must stay in order?

Find the business object whose events must be handled in sequence, such as an order, an account, or a device. That identity is the natural key.

Question 2

What must be processed together?

If a consumer counts or joins events by some identity, that identity should be the key so the events meet in one partition.

Question 3

Are there many distinct values?

A good key has many different values, so the hash can spread them evenly across partitions.

Question 4

Is the traffic even?

Even with many values, one very busy key can overload a single partition. Check how the traffic is distributed.

Question 5

Is it stable?

The key should not change during the life of the object. If it changes, events for the same object scatter.

Examples of good keys

Business AreaGood KeyWhy It Works
Online ordersOrder number or customer numberKeeps one order’s or customer’s events in sequence
BankingAccount numberBalance changes are applied in the right order
Ride hailingDriver or trip identityLocation updates never jump backwards
Factory sensorsMachine identityEach machine’s readings stay in time order
User profilesUser identityLatest profile state can be kept per user

Examples of poor keys

Poor KeyProblem
Country codeOnly a small number of values, and one country may dominate the traffic
True or false flagOnly two values, so at most two partitions are ever used
Current dateAll events of one day go to one partition, creating a daily hot spot
A unique event numberNo grouping at all, so it gives no order and no co-location
A constant placeholderEvery event lands in the same partition
i
Helpful Note

A useful rule of thumb: the key should be the identity of the “thing” the event is about, not a category the thing belongs to.

7Hot Keys and Uneven Load

Keys keep related events together, but sometimes “together” becomes too much of a good thing.

What is a hot key?

A hot key is a key that receives a far larger share of the traffic than the others. Since all events with the same key go to one partition, a hot key makes that partition much busier than its neighbours. The partition’s leader broker works harder, and the single consumer reading that partition falls behind, even though the other consumers in the group may be idle.

How hot keys appear

One giant customer

A platform serving many shops may have one enormous shop that generates most of the events. If the shop identity is the key, that shop’s events overload one partition.

A viral item

A single product or video suddenly attracts millions of views in an hour. If the item identity is the key, one partition takes the whole storm.

A default key gone wrong

A bug or missing value causes many events to be sent with the same empty or placeholder key, sending everything to one partition.

flowchart LR
  subgraph Even["Evenly spread keys"]
    E0["P0 - 25 percent"]
    E1["P1 - 25 percent"]
    E2["P2 - 25 percent"]
    E3["P3 - 25 percent"]
  end
  subgraph Hot["One hot key"]
    H0["P0 - 75 percent"]
    H1["P1 - 10 percent"]
    H2["P2 - 8 percent"]
    H3["P3 - 7 percent"]
  end
        
FIG 3 — Balanced load compared with a hot key
Simple Analogy

A postal area with one giant company receiving thousands of parcels a day forces one delivery van to carry most of the load, while the vans for quiet streets travel almost empty. Adding more vans does not help, because the company’s parcels all belong to one route.

!
Common Mistake

Measuring only the average traffic of a topic. Averages hide hot partitions. Always look at each partition separately, especially the busiest.

8Fixing Hot Keys: Salting and Other Ideas

When one key is too popular, there are ways to spread its load, though each has a price.

Idea 1: Add a small extra part to the key

This approach is often called salting. For the giant customer, instead of using only the customer identity as the key, the producer appends a small number, such as one to ten, chosen in rotation. The events of that customer now spread over up to ten partitions. The price is that order is now guaranteed only inside each of the ten sub-groups, not across the whole customer. Consumers that need the full picture must combine results from all the sub-groups.

Idea 2: A custom partitioner

The producer can use its own rule that treats known heavy keys specially, giving them several partitions, while ordinary keys follow the normal rule. This needs care, because every producer must use exactly the same rule.

Idea 3: Choose a finer key

Sometimes a more detailed identity exists. Instead of the shop, use the shop together with the order number. Events for one order stay in sequence, while the shop’s total load spreads across many partitions.

Idea 4: Give the busy topic more partitions

More partitions help spread many keys but do not help a single key, because one key still maps to one partition. This idea fixes crowding among many keys, not the dominance of one.

FixWhat It SolvesWhat You Give Up
Salting the keyOne key spread over several partitionsOrder across the whole key is lost; consumers must merge results
Custom partitionerSpecial handling for known heavy keysMore code; every producer must use the same rule
Finer-grained keyNatural spread using a more detailed identityOrder is kept only at the finer level
More partitionsCrowding among many keysDoes not help a single dominant key; changes key mapping
i
Helpful Note

Ask first whether strict order for that giant key is really needed. Many designs discover that order is only required at a finer level, such as per order, which solves the hot key naturally.

9Keys and the Number of Partitions

The connection between a key and its partition depends on how many partitions exist. This fact surprises many teams.

The map depends on the count

Remember that the partition is the remainder after dividing the hash by the partition count. If the count changes from six to eight, the remainder for the same key changes too. A customer whose events always landed in partition 3 may now land in partition 5.

What goes wrong when you add partitions

Kafka lets you increase the partition count of an existing topic, but it does not move old events. Old events for a customer stay in partition 3, while new events now go to partition 5. For a while, the events of one customer are split across two partitions, and a consumer might read the new partition faster than the old one, seeing events out of order. Also, programs that keep running totals per key in memory may now receive the same key on a different consumer, without its history.

1

Before growth

The topic has six partitions. Every event for customer 4711 goes to partition 3.

2

The count is raised

The topic is changed to eight partitions. Old events remain where they were written.

3

The key map shifts

New events for customer 4711 may now land in partition 5, while the older ones stay in partition 3.

4

Consumers see a split history

Two different consumers may read the same customer’s old and new events at different speeds, breaking the order for that period.

Simple Analogy

A postal service divides a city into six delivery zones by the last digit of the postcode. When it suddenly redraws the map into eight zones, your street may now belong to a different van. Letters already in the old van still need delivering, so for a while two vans serve your street, and the order of delivery can get muddled.

ANTI-PATTERN-01 Avoid
Problem

Adding partitions to a keyed topic during busy hours, while consumers rely on strict order per key or keep local state per key.

Why It’s Harmful

Keys now map to different partitions, so ordering can break and stored state can end up on the wrong consumer.

Correct Approach

Plan the partition count generously at creation. If growth is unavoidable, do it during quiet periods, or create a new topic with the larger count and migrate carefully.

10Keys Must Be Consistent Across Producers

For the promise “same key, same partition” to hold, every producer must calculate the partition in exactly the same way.

The hidden danger

Different programming languages and client libraries may use slightly different default rules for hashing keys. Two producers written in different languages, or using different libraries, could send the same customer’s events to different partitions. Similarly, if one producer serializes the customer number as text and another as a binary number, the bytes differ, the hash differs, and the events scatter.

How to stay safe

1

Agree on the key format

Decide exactly how each key is written, such as a plain text customer number without extra spaces or changes in letter case.

2

Use the same serializer

Make every producer of that topic convert keys to bytes in the same way.

3

Check the partitioner rule

Confirm that all client libraries in use apply the same default hashing rule, or configure them to use the same one.

4

Test with sample keys

Send the same sample keys from every producer and confirm they land in the same partitions.

Simple Analogy

If one sorting office writes postcodes with a space in the middle and another writes them without, a machine may treat them as different codes and send the letters to different vans. Everyone must agree on the exact spelling of the postcode.

!
Common Mistake

Treating “12345” and “012345”, or “Alice” and “alice”, as the same key. To the hash they are different bytes, so they go to different partitions. Clean and standardise keys before sending.

11Keys and Consumer Groups

Keys shape the work of consumers as much as the work of producers.

One partition, one reader per group

Within a consumer group, each partition is read by exactly one member at a time. Because a key always goes to one partition, all events for that key are handled by one consumer of the group, in order. This is powerful: the consumer can keep running totals, a shopping cart, or a recent history for each key in its own memory, knowing no other member of the group will receive that key’s events.

Moves during rebalances

When a consumer joins or leaves, partitions are redistributed among the members, an event called a rebalance. A key’s partition may then move to another consumer. Well-built consumers recover their state, for example by reading it again from Kafka, or from a store, before continuing.

flowchart LR
  K1["Key: customer 1"] --> P0["Partition 0"]
  K2["Key: customer 2"] --> P1["Partition 1"]
  K3["Key: customer 3"] --> P2["Partition 2"]
  K4["Key: customer 4"] --> P0
  P0 --> C1["Consumer A"]
  P1 --> C2["Consumer B"]
  P2 --> C3["Consumer C"]
        
FIG 4 — Keys map to partitions, and partitions map to consumers
Simple Analogy

A hospital assigns each patient to one nurse per shift. The nurse remembers the patient’s condition and treats the patient’s records in order. If the nurse goes home, the patients are reassigned, and the replacement reads the notes before continuing.

i
Helpful Note

Because different groups read independently, the billing team and the analytics team each get every key’s events in order, in their own group, without disturbing each other.

12Keys and Log Compaction

The key has a second important job: it identifies the “thing” in topics that keep only the latest state.

What is compaction?

Normally, Kafka deletes old events after a retention period. With log compaction, Kafka instead keeps at least the latest event for every key and may remove older events with the same key. The topic then behaves like a table of current values: for every key, the most recent value is always available, even after a very long time.

An example

Suppose a topic stores each customer’s current address, keyed by customer number. The customer moves three times, so three events exist with the same key. After compaction, only the latest address remains for that customer. A brand-new application can read the compacted topic from the beginning and quickly rebuild the current address of every customer, without replaying every historical change.

Deleting with a tombstone

To remove a key completely, a producer sends an event with that key and an empty value, called a tombstone. Compaction eventually removes the key entirely, after giving readers some time to see the deletion.

Simple Analogy

A contact list keeps only each person’s newest phone number. Older numbers are crossed out and finally erased. If a friend asks to be removed from the list, a note is written saying “no entry”, and after some time the whole line is erased.

!
Common Mistake

Enabling compaction on a topic where events have no keys. Compaction works by key, so keyless events cannot be compacted and the setting will not do what you expect.

13Keys, Joins, and Stream Processing

When streams are combined or counted, keys decide which events can meet each other.

Counting and grouping

Stream processing applications often count events per identity, such as orders per customer in the last five minutes. To do this correctly and quickly, all events of one customer must reach the same processor. The key makes this possible. If the events were not keyed by customer, the application would first need to re-key them, which creates an extra topic and extra work.

Joining two streams

Suppose one topic holds orders and another holds payments, and you want to match each payment to its order. For the match to happen inside one processor, both topics must use the same key, such as the order number, and both must have the same number of partitions. This arrangement is called co-partitioning. It guarantees that an order and its payment arrive in the same partition number of their respective topics, and therefore at the same processor.

flowchart TD
  O["Orders topic - keyed by order number"] --> J["Join processor for partition 2"]
  P["Payments topic - keyed by order number"] --> J
  J --> R["Matched order and payment"]
        
FIG 5 — Matching keys and matching partition counts let streams be joined
Simple Analogy

Two teams of clerks handle order forms and payment slips separately. To match them quickly, both teams must file their papers in cabinets sorted the same way, by order number, with the same number of drawers. Then a matching form and slip always sit in drawers with the same number, and one clerk can compare them.

i
Helpful Note

If streams use different keys, stream processing tools can re-key them for you by writing to an intermediate topic. This works, but adds traffic and delay, so choosing matching keys from the start is cheaper.

14Security and Privacy of Keys

A key is stored with every event, in plain sight of anyone allowed to read the topic. Treat it with care.

Keys are not secret

The key travels with the event and is stored on disk, often for days or longer. Anyone with permission to read the topic can see it. Therefore, avoid using sensitive personal data, such as national identity numbers, email addresses, or card numbers, as raw keys. If you need such an identity to group events, use a stable internal identifier, or a protected version of the value, so that the actual sensitive data is not repeated in every event and across every backup.

Access rules

Kafka can require applications to prove their identity and can restrict which identities may read or write each topic. These rules apply to the whole topic, including its keys and values. If some data is more sensitive than the rest, keep it in a separate topic with tighter access.

Simple Analogy

The postcode on a parcel is visible to every sorter along the way, so it should not contain private information. A random customer number printed on the label is safer than the customer’s full name and home address.

!
Common Mistake

Using an email address as a key because it is unique and convenient. It spreads personal data into logs, monitoring tools, and backups, and makes later deletion requests much harder to satisfy.

15Monitoring Keys and Their Effects

You cannot see keys directly on a dashboard, but you can see their effects.

Skew
Whether traffic is even across partitions
Lag
How far each partition’s reader trails the newest event
Size
Whether some partitions grow much larger than others

What to watch

Watch the volume of data written to each partition. A partition that receives far more than its siblings points to a hot key. Watch consumer lag per partition rather than only in total, since one lagging partition can hide inside a healthy-looking average. Watch the disk size of each partition, because a partition with a hot key grows much faster. If a topic uses compaction, also watch how well compaction keeps up.

Investigating a hot key

When you suspect skew, sample some events from the busy partition and count which keys appear most often. Often a single identity, a missing value, or a placeholder key accounts for most of the traffic. Fixing that one key can restore balance to the whole topic.

i
Helpful Note

Set an alert when the busiest partition carries a much larger share than the average partition for a sustained period. Brief spikes are normal, but a steady imbalance means the key design needs attention.

16Advantages and Trade-offs of Using Keys

Keys are powerful, but they are a commitment.

Advantages

  • Guarantee order for all events that share a key
  • Keep related events together for counting, joining, and state building
  • Spread many different keys evenly across partitions
  • Enable log compaction to keep the latest state per key
  • Let consumers keep local state per key safely
  • Work without any coordination between producers

Disadvantages / Trade-offs

  • A hot key can overload a single partition
  • Order is lost across different keys and across partitions
  • Changing the partition count changes where keys land
  • All producers must follow exactly the same key format and rule
  • Keys are stored openly with every event, so sensitive data must be avoided

17More Anti-Patterns and Best Practices

Most key problems repeat across teams. Here are the most common.

ANTI-PATTERN-02 Avoid
Problem

Using a low-variety value, such as a country or a status, as the key.

Why It’s Harmful

Only a few partitions receive data, so most of the cluster’s capacity is wasted and a few partitions are overloaded.

Correct Approach

Use the identity of the individual object, such as an order or a device, which has many distinct values.

ANTI-PATTERN-03 Avoid
Problem

Sending related events with different keys and expecting them to be read in order.

Why It’s Harmful

Different keys can land in different partitions, which have no ordering relationship. A “paid” event may be read before its “created” event.

Correct Approach

Use the same key, such as the order number, for every event about one business object.

ANTI-PATTERN-04 Avoid
Problem

Letting a key change during the life of an object, such as switching from a temporary identifier to a permanent one.

Why It’s Harmful

Events before and after the change go to different partitions, breaking the order and splitting the history.

Correct Approach

Choose an identifier that is assigned once and never changes, and use it from the very first event.

ANTI-PATTERN-05 Avoid
Problem

Using a personal detail such as an email address, phone number, or national identity number as the key.

Why It’s Harmful

Sensitive data is copied into every event, log, and backup, and becomes hard to protect or delete.

Correct Approach

Use an internal identifier that has no meaning outside your system.

Best practices at a glance

Habit 1

Key by business identity

Use the identity of the object whose events must stay in order.

Habit 2

Prefer many distinct values

High variety lets the hash spread traffic evenly.

Habit 3

Keep keys stable and clean

Fix the format, case, and spacing, and never change a key mid-life.

Habit 4

Standardise across producers

Use the same serializer and partitioning rule everywhere.

Habit 5

Plan the partition count early

Choose it with headroom so you rarely need to change it.

Habit 6

Watch each partition

Track traffic and lag per partition to catch hot keys early.

Habit 7

Protect privacy

Never place sensitive personal data in a key.

Habit 8

Skip keys when order is irrelevant

Let keyless events spread freely for the best balance and batching.

“Choose the key to match the order you must protect, and let the hash share out everything else.”

18A Real-World Design Walk-Through

Let us design the keys for an online marketplace step by step.

1

List the topics

The marketplace has topics for orders, payments, shipments, and product views.

2

Decide what must stay in order

The life of one order, from creation to payment to shipment, must be processed in sequence. So the order number becomes the key for orders, payments, and shipments.

3

Align partition counts

Because the payments service joins payments with orders, both topics use the same key and the same number of partitions, allowing co-partitioned processing.

4

Leave product views keyless

Product view events are independent and huge in number. They are sent without a key, spread evenly, and batched efficiently.

5

Check for hot keys

Order numbers are unique per order, so no single key dominates. If instead the seller identity were used, a giant seller could overload a partition.

6

Keep the latest seller profile

A separate compacted topic, keyed by seller identifier, holds the latest profile of each seller so new services can load them quickly.

7

Protect privacy and monitor

Keys are internal identifiers, not emails. Dashboards show per-partition volume and lag, with alerts for sustained imbalance.

flowchart LR
  OS["Order Service"] -->|"key: order number"| OT["Orders topic"]
  PS["Payment Service"] -->|"key: order number"| PT["Payments topic"]
  WS["Website"] -->|"no key"| VT["Product views topic"]
  SP["Seller Profile Service"] -->|"key: seller id"| ST["Seller profiles - compacted"]
  OT --> JN["Join processor"]
  PT --> JN
        
FIG 6 — Different key choices for different kinds of events

19Frequently Asked Questions

Q1What is a partitioning key in one sentence?

It is the optional identity attached to a Kafka event that is used to calculate which partition stores the event, so events with the same key stay together and in order.

Q2Is the key required?

No. Without a key, the producer spreads events across partitions for balance. Use a key only when you need ordering, grouping, joining, or compaction by identity.

Q3Must every key be unique?

No. Keys should be shared by all events that belong together. A unique key for every event gives no grouping and no useful order.

Q4Does the same key always go to the same partition?

Yes, as long as the number of partitions and the partitioning rule stay the same. If you add partitions, the mapping changes for new events.

Q5Can I choose the partition myself?

Yes. A producer can name an exact partition, or plug in a custom partitioning rule. This is rarely needed and requires every producer to follow the same rule.

Q6What is a hot key?

A key that receives far more traffic than others, overloading the single partition it maps to. It can be fixed by choosing a finer key, adding a small extra part to the key, or using a custom rule for heavy keys.

Q7Does the key have to be part of the value?

No. The key is a separate field. Many designs repeat the identity inside the value too, so that readers can see it easily, but that is a design choice, not a requirement.

Q8What happens to ordering when I use a null key?

Events without a key are spread across partitions, so there is no order between them. Order exists only inside each partition.

Q9Why did my events for one customer land in different partitions?

Common reasons are that some events were sent without a key, that keys differ in format or spelling, that different producers use different hashing rules, or that the partition count was changed.

Q10Can I put personal data in a key?

It is best not to. Keys are stored openly with every event. Use an internal identifier instead, so sensitive data is not spread through logs and backups.

20Summary and Key Takeaways

We began with a post office that sorts letters purely by postcode, sending related letters to the same sack and van. The partitioning key is Kafka’s postcode. It is a small identity on each event that is turned into a partition number by a fast, fixed calculation, so all events with the same key travel together and in order. Keys give you ordering per object, allow counting, joining, and local state, and make compaction possible. They also come with responsibilities: choose a key with many distinct values and even traffic, keep the format and rule identical across producers, plan the partition count early, never rely on order across keys, and never hide sensitive data in a key. Choose the key with the same care you would give to designing a database index, because in Kafka it quietly shapes everything that follows.

Key Takeaways

  • A key picks the partition — the producer hashes the key and fits it to the partition count, so the same key always lands in the same partition while the count is unchanged.
  • Order exists per key — events sharing a key stay in sequence, but there is no order between different keys or across partitions.
  • Keys are optional — skip them when order does not matter, and let events spread evenly with large batches.
  • Choose by business identity — use a stable identifier of the object whose events must stay together, with many distinct values and balanced traffic.
  • Beware of hot keys — one dominant key overloads one partition, and fixes include finer keys, salting, or custom rules, each with a trade-off.
  • Changing partitions moves keys — adding partitions alters the key map for new events, so plan the count early and avoid changes during busy periods.
  • Keep keys consistent and private — use identical formats and rules in every producer, use matching keys and counts for joins, and never place sensitive personal data in a key.