AlgoMaster Logo

Event Keys and Partitioning Strategy

High Priority9 min readUpdated November 11, 2026
Listen to this chapter
Unlock Audio

Designing the event payload is only part of the process. We also need to decide where each event should be stored within a Kafka topic.

This decision matters because Kafka divides topics into partitions, and each partition is an independent, ordered sequence of records.

The way events are distributed across these partitions affects ordering, throughput, load balancing, and how easily consumers can scale.

In this chapter, we'll explore how Kafka uses record keys to select partitions, how to choose the right key for your application, and how to avoid common partitioning problems.

1. Understanding Event Keys

Every Kafka record can contain a key and a value.

The value holds the actual event data, while the key typically identifies the entity associated with that event.

For example, consider an OrderPlaced event:

We might publish this record with:

Here, ORD-123 is the record key, and the JSON object is the record value.

The key is separate from the event payload. Kafka stores both as part of the record, along with metadata such as the timestamp, partition, and offset.

A record key serves two important purposes:

  1. It helps determine which partition receives the record.
  2. It allows related records to be grouped in the same partition, preserving their order.

Kafka doesn't require every record to have a key. However, choosing one becomes important when your application depends on ordering or entity-based processing.

2. How Kafka Selects a Partition

Suppose our orders topic has four partitions:

When a producer sends an event, Kafka's producer partitioning logic determines which partition should receive it.

With the standard key-based strategy, the producer hashes the serialized record key and uses the result to select a partition.

Conceptually:

The actual implementation handles hash values carefully to ensure a valid partition index.

For example:

Notice that both records with the key ORD-101 go to Partition 2.

This is intentional.

As long as the partition count and partitioning strategy remain unchanged, the same serialized key maps to the same partition.

The producer performs this calculation before sending the record. Kafka brokers don't need to inspect the event payload to decide where it belongs.

The producer can also explicitly specify a partition, overriding normal key-based selection.

3. Why Keys Matter for Ordering

Kafka guarantees ordering within a partition, not across partitions.

Suppose our Order Service publishes three events:

All three events belong to the same order.

If we use orderId as the key, they can be routed to the same partition:

A consumer reading this partition encounters these records in offset order.

Now suppose we publish the events without consistent keys:

Different consumers may process these partitions independently.

The shipping event might be processed before the payment event, even if the producer originally published them in the correct order.

That could create problems if downstream processing depends on the order lifecycle.

Using a consistent key keeps related records together.

However, there's an important distinction: partition ordering doesn't automatically guarantee correct business ordering.

4. Choosing the Right Partition Key

The best partition key depends on how your application processes events.

A useful starting question is:

Which events must stay together, and in what order must they be processed?

Let's consider a few examples.

Example 1: Order Processing

For an order processing system, we might use:

All lifecycle events for an order are routed to the same partition.

This is useful when consumers maintain order-level state or depend on the sequence of changes.

Example 2: Banking Transactions

Suppose we're building a system that processes account transactions.

We might choose:

All transactions affecting the same account can be processed in order.

This can simplify balance calculations and other account-specific operations.

However, ordering alone doesn't prevent duplicate transactions or concurrent updates outside that processing path. Financial systems still need appropriate idempotency and consistency controls.

Example 3: User Activity Tracking

For a system tracking user activity, we might use:

Events such as PageViewed, ProductClicked, and CheckoutStarted for the same user can be processed together.

This is useful for building user sessions and maintaining per-user state.

Notice that each example chooses the key based on the entity whose events need to remain together.

There's no universally correct partition key. The right choice depends on the application's processing requirements.

5. What Happens When a Record Has No Key?

Not every Kafka event requires ordering by a particular entity.

Consider a topic collecting independent application metrics:

If we're simply aggregating request counts and latency statistics, we may not care which partition receives each event.

In this case, we can publish records with a null key.

Kafka's default Java producer uses a sticky partitioning strategy for keyless records, sending records to a selected partition for a period of batching before switching partitions.

This improves batching efficiency and reduces the overhead of sending many small requests.

Over time, traffic can be distributed across partitions without preserving ordering for individual entities.

The important difference is:

  • Keyed records: Partition selection is based on the key.
  • Keyless records: The producer distributes records using its keyless partitioning strategy.

Use keys when related events need consistent placement. Otherwise, keyless publishing is often sufficient.

6. Balancing Ordering and Parallelism

Partitioning introduces an important trade-off between ordering and parallel processing.

Suppose our topic has eight partitions.

A consumer group can assign these partitions to multiple consumers, allowing records to be processed in parallel.

With conventional partition assignment, each partition is owned by one consumer within the group at a time.

If we increase the number of consumers, we can process more partitions concurrently.

However, Kafka won't automatically split a single partition across multiple consumers in the same group.

If every event uses the same key, all records may end up in one partition.

Even if the topic has eight partitions, most of the available parallelism goes unused.

This is why a good partition key should satisfy two goals:

  1. Preserve ordering where the application needs it.
  2. Distribute work across enough partitions to support the required throughput.

These goals sometimes conflict.

7. Avoiding Hot Partitions

A hot partition occurs when one partition receives significantly more traffic than others.

Suppose an e-commerce application processes orders from thousands of customers.

If we use customerId as the partition key, most customers may generate only a few orders per day.

But suppose one large enterprise customer generates thousands of orders per second.

All events for that customer will be routed to the same partition.

Partition 2 now carries most of the workload.

Its consumer may fall behind while other consumers remain mostly idle.

Adding more consumers won't necessarily solve the problem because the hot partition still belongs to one consumer in the group.

How Do We Fix This?

The first option is to reconsider the partition key.

If the application only requires ordering within individual orders, using orderId instead of customerId may distribute traffic more evenly.

But if strict customer-level ordering is required, changing the key would violate that requirement.

Another option is key salting, where we add a suffix to distribute events across partitions:

This can spread the load, but it also breaks the original per-customer partition ordering.

Consumers must then handle the additional complexity, potentially including reordering or coordination.

8. What Happens When You Increase Partitions?

Kafka allows you to increase the number of partitions in an existing topic.

Suppose our topic originally has four partitions.

A key might be routed using:

Later, we increase the topic to eight partitions:

The same key may now map to a different partition.

For example:

Existing records remain in Partition 2, while new records may arrive in Partition 6.

This can break ordering assumptions because two consumers may process records for the same entity concurrently.

Increasing partitions is therefore not always a harmless scaling operation.

9. Custom Partitioning Strategies

Kafka also allows applications to implement custom partitioners.

A custom partitioner can be useful when the default hash-based approach doesn't meet specific requirements.

For example, an application might need to route records using business-specific rules or maintain compatibility with an existing partitioning scheme.

However, custom partitioning introduces additional responsibilities.

Every producer must follow the same routing rules, and changes must be coordinated carefully.

For most applications, Kafka's default partitioning behavior is sufficient.

Start with a simple, meaningful key and introduce custom partitioning only when there's a clear requirement.

10. Practical Guidelines

When choosing event keys and designing a partitioning strategy, keep these principles in mind:

  1. Identify ordering requirements first. Determine which events must be processed in sequence.
  2. Choose a stable business identifier. Prefer identifiers such as orderId, accountId, or userId when they match the required ordering scope.
  3. Use consistent key serialization. Producers must generate the same key bytes for the same logical identifier.
  4. Avoid low-cardinality keys. Keys such as country or status may concentrate traffic into a small number of partitions.
  5. Watch for hot keys. Even a high-cardinality key can create uneven load if a few entities generate most of the traffic.
  6. Plan partition counts carefully. Increasing partitions can change key placement and affect ordering.
  7. Monitor partition-level metrics. Track throughput, consumer lag, and traffic distribution to identify imbalances.

The goal isn't perfectly equal traffic across every partition. It's sufficient distribution without sacrificing the processing guarantees your application needs.

Key Takeaways

Event keys are an important part of Kafka system design because they determine how related records are distributed across partitions.

A good partition key keeps events that require ordering together while allowing unrelated events to be processed in parallel.

For an order processing system, orderId is often a natural choice. For account transactions, accountId may be more appropriate. For independent events with no entity-level ordering requirements, a null key may be sufficient.

The main trade-off is between ordering, throughput, and parallelism.

Understanding this trade-off helps you design Kafka topics that scale without introducing unnecessary complexity or inconsistent event processing.

Quiz

Event Keys and Partitioning Strategy Quiz

10 quizzes