Keys, Partitioning and Ordering

Keys, Partitioning and Ordering in Apache Kafka: The message key is the single most consequential field in a Kafka record, and it is optional — which is why it…

The message key is the single most consequential field in a Kafka record, and it is optional — which is why it is so often wrong.

What the key does

The key is not an identifier for lookups. Kafka never queries by key. The key exists to decide which partition a record goes to:

partition = hash(keyBytes) % numberOfPartitions

Same key → same partition → same log → guaranteed relative order.

Null keys mean no ordering

If the key is null, the default partitioner distributes records across partitions to balance load (historically strict round-robin; modern clients use a sticky strategy that fills one partition's batch before moving on). Either way, consecutive records for the same logical entity can land on different partitions.

key = null, three events for order-42:

 p0: [ Shipped ]
 p1: [ Created ]
 p2: [ Paid    ]

Three consumers, three partitions → any interleaving is legal.
A consumer may process Shipped before Created.

If a consumer of yours has ever had to handle "update for a record that does not exist yet", a null key is a prime suspect.

Choosing a key

Ask one question: what is the unit that must be processed in order? That is your key.

DomainReasonable keyWhy
Order lifecycle eventsorder_idState transitions per order must be sequential
Account ledgeraccount_idBalance depends on operation order
Device telemetrydevice_idReadings per device should stay in sequence
Page views for analyticsnullAggregate counts do not care about order
Change-data-capture rowsprimary keyLast write per row must win

Note the deliberate null: if ordering genuinely does not matter, a null key gives you the best load spread. Keying "just in case" is not free.

Key skew

Partitioning by hash assumes keys are reasonably uniform. When they are not, you get a hot partition.

key = country_code, 6 partitions

 p0: ███████████████████████████  US   (70% of traffic)
 p1: ███                          DE
 p2: ██                           FR
 p3:                              (idle)

The consumer owning p0 is the bottleneck; the cluster looks under-utilised while one broker's disk fills. Symptoms are lag on a single partition and uneven broker disk usage.

Fixes, in order of preference:

  1. Pick a finer-grained key. user_id instead of country — usually the real fix.
  2. Composite key such as tenant_id + entity_id, when a single tenant dominates.
  3. Salted key (user_id + ":" + n for small n) when you can accept ordering only within each salted sub-stream.

Option 3 trades away part of your ordering guarantee. Do it knowingly.

Custom partitioners

You can implement Partitioner to override the mapping — for example to pin a tenant to dedicated partitions, or to keep a stable mapping when partition count changes. The cost is that this logic now lives in every producer and must stay consistent across languages and versions. Prefer a good key over a clever partitioner.

Repeating the trap from Module 1, because it matters most here

The default mapping includes % numberOfPartitions. Increase the partition count and every existing key can move.

before (3 partitions):  "user-7" → p1   history lives here
after  (4 partitions):  "user-7" → p3   new events go here

Nothing errors. Consumers just start processing one entity's events from two partitions concurrently, and per-key ordering is gone for the overlap window. This is why partition count is a design decision, not a scaling dial.

Headers, and what does not belong in the key

Use record headers for metadata: trace IDs, schema hints, source system, event type. Do not encode those into the key — anything you add to the key changes the partition assignment.


Exercise: A multi-tenant SaaS product publishes audit-events keyed by tenant_id to 12 partitions. One enterprise tenant produces 60% of all events; their partition lags by hours while other consumers idle. Propose a keying change, state precisely which ordering guarantee you give up, and explain what the consumer must now tolerate.