Course contents

07. Messaging and Event-Driven Systems Lesson 5 of 10

Kafka Partitions

Partitions as the unit of parallelism and ordering: key hashing, hot partitions from skewed keys, why more partitions do not split a key, and remapping.

15 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Within a consumer group, each partition is read by one consumer, so partitions cap parallelism.
  • A record’s key is hashed to a partition; the same key always lands on the same partition while the count is unchanged.
  • Order is guaranteed inside a partition and never across partitions.
  • A skewed key makes a hot partition; adding partitions does not split one key.
  • Changing the partition count remaps keys (most of them with hash mod N), which can reorder a key’s records.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A Kafka topic is split into partitions. Each partition is its own append-only log with its own offsets, stored on one broker (the leader) and replicated to others. Producers append each record to exactly one partition; consumers read partitions independently. Kafka Streams, Redpanda, Amazon Kinesis (shards), Azure Event Hubs and Apache Pulsar (partitioned topics) use the same idea.

Why it exists

One log on one broker, read by one consumer, has a ceiling: the write speed of that broker and the processing speed of that consumer. Partitions let a topic grow past it. Different partitions can live on different brokers and be read by different consumers at the same time, while each partition stays strictly ordered. The topic gives up global order in exchange for horizontal scale.

How it works

Choosing a partition. The producer client decides. If the record has a key, Kafka’s default partitioner computes murmur2(keyBytes), makes it positive and takes it modulo the partition count. The same key therefore always lands on the same partition while the count stays the same. Records without a key are spread across partitions; current Java clients fill a batch for one partition before moving to the next, which gives larger batches than strict round robin. Producers can also supply a custom partitioner or name the partition explicitly.

Reading partitions. Within a consumer group, each partition is assigned to exactly one consumer. A consumer can own several partitions, but a partition is never split between two members of one group. So a group can use at most as many consumers as there are partitions; extras sit idle (see the consumer groups lesson).

Ordering. A partition is read in offset order by its one consumer, so records of one key are stored and delivered in the order they were written. Across partitions there is no order at all. Producer retries could reorder records within a partition, which is why idempotent producers (the default since Kafka 3.0) attach sequence numbers that the broker checks.

Hot partitions. Load per partition is the sum of the keys that hash to it. When keys are skewed (one big tenant, one viral product, a default value such as null or "unknown" used as the key), one partition gets much more than its share. Its consumer falls behind while others are idle. Adding partitions spreads the other keys more thinly but cannot split a single key.

Changing the partition count. You can add partitions to a topic but not remove them. Adding changes hash mod N, so most keys move: from 3 to 4 partitions about three quarters of keys land elsewhere. Old records stay where they were, so for a while a key has unprocessed records on two partitions, possibly read by two consumers in either order. Consumers that keep per-key state (Kafka Streams state stores, in-memory aggregates) find that state on the wrong instance.

When to use it

  • Any topic whose throughput or consumer work exceeds what one consumer can do.
  • When related events must stay in order: key by the entity (order id, account id, device id) so they share a partition.
  • When consumers keep per-key state locally: partitioning routes every event of a key to the same consumer.

When not to

  • Low-volume topics: one or a few partitions keep things simple and still allow a few consumers.
  • When you need a global order of all events: that requires one partition, and therefore one consumer, or a sequencing step elsewhere.
  • When work items are independent and short: a work queue with competing consumers scales per message, not per partition (Kafka 4.x share groups, KIP-932, also move in this direction).

Trade-offs

Choice You gain You pay
More partitions More consumers in parallel, more brokers used Broker memory and file handles, replication traffic, slower recovery and rebalances
Fine-grained key (order id) Even spread, per-entity order No order across entities (for example across one customer’s orders)
Coarse key (tenant id) Order across everything of a tenant Hot partitions when tenants differ in size
No key Best spread, biggest batches No per-entity order at all
Salting a hot key (key#0…#7) Spreads one key’s load Order only within each salt; readers must merge

Alternatives

  • Work queues (SQS, RabbitMQ, Kafka share groups): any consumer takes any message, so parallelism is not tied to partitions; per-key order needs FIFO features such as SQS FIFO message groups.
  • Separate topics per heavy tenant: isolates a hot key at the price of more topics to manage.
  • Consistent hashing in your own routing layer: moves fewer keys when the number of buckets changes; Kafka’s default partitioner does not do this.

Failure modes

  • Hot partition: one partition’s lag grows while total utilisation looks fine. Monitor lag and bytes in per partition, not just per topic.
  • Null or constant keys: a missing key that defaults to the same value sends everything to one partition.
  • Repartition surprise: adding partitions to fix lag reorders keys and breaks per-key state.
  • Too few partitions: you cannot add consumers to catch up after an incident, because extras would be idle.
  • Too many partitions: long leader elections and rebalances, and producers spread data so thinly that batches stay small.

In production

Estimate partitions as peak throughput ÷ what one consumer sustains (measured, not guessed), then add headroom for growth so you rarely change it. Watch per-partition lag (consumer lag exporters, Burrow, Cruise Control or your platform’s metrics) and per-partition bytes in. Keep the partitioner identical across all producers of a topic (different languages’ clients hash differently unless configured to match). If you must increase partitions on a keyed topic, plan it: pause or drain producers, or create a new topic and migrate.

Common misconceptions

  • "More consumers always means more throughput." Not beyond the partition count.
  • "Adding partitions fixes a hot partition." It spreads other keys; the hot key stays on one partition.
  • "Kafka orders a topic." It orders each partition. Two keys on different partitions have no defined order.
  • "Partitions are only about speed." They also define ordering and placement, which is why the count is hard to change.

Interview angle

When you put Kafka in a design, say what the key is and why ("key by order id so an order’s events stay in order"), estimate the partition count from throughput, and mention hot keys before the interviewer does. A strong answer notes that consumers in a group are capped by partitions, that order is per partition only, and that repartitioning moves keys, so you size with headroom.

Model assumptions

The simulation in this lesson is a simplified model, not a benchmark. Producers send records at random (Poisson), 75 per second (15 in the key-hashing step). Each partition is a queue with exactly one consumer; each consumer handles one record at a time, about 22 ms of work (lognormal, cv 0.3) plus a 3 ms fetch hop, so roughly 40 records per second. Keys come from 1,000 equally likely values, or from 100 Zipf-distributed values (exponent 2) in the hot-key steps, where the hottest key carries about 60% of records. The simulated partitioner is a hash ring with 64 points per partition: shares come out within about ±15% of even, and adding a partition moves only the keys it takes over. Kafka’s default murmur2 mod N moves most keys; that and the key-hashing and moved-key animations are scripted illustrations, not simulated. In the challenge each partition holds at most 100 unprocessed records and rejects the rest, standing in for a retention-size budget. Not modelled: broker limits, replication, batching and compression, consumer fetch sizes. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One partition, one reader

    The orders topic has a single partition. Producers append 75 records per second to it.

    In a consumer group, a partition is read by at most one consumer at a time. That is how the log keeps its order: one reader, reading offsets in sequence. So this topic can only be processed as fast as Consumer 0 goes, about 40 records per second.

    The gap, 35 to 40 records per second, piles up as consumer lag: records written but not yet processed. Adding consumer machines would not help; there is no second partition to give them.

    Scene: Producers send 75 records per second through the partitioner to a single partition, P0. Consumer 0 processes about 40 per second, so the backlog in P0 grows steadily.

    Key idea: A partition is read by one consumer per group, so one partition caps processing at one consumer’s speed.

  2. 2. Split the topic into partitions

    The topic now has three partitions, each with its own consumer. Each partition is an independent log on the broker with its own offsets, and each can be read by a different consumer in parallel.

    The partitioner sends each record to one partition, so each gets roughly a third of the traffic, 20 to 30 records per second, well within one consumer’s 40. Total capacity is now about 120 records per second, and lag stays near zero.

    Partitions are the unit of parallelism: the number of partitions is the most consumers a group can use.

    Scene: The topic has three partitions, P0, P1 and P2, each read by its own consumer. Each partition receives roughly a third of the 75 records per second and the backlogs stay near empty.

    Key idea: Partitions are the unit of parallelism: more partitions, more consumers working at once.

  3. 3. The key picks the partition

    Which partition does a record go to? If it has a key (here, the customer id), the producer hashes the key and maps the hash to a partition. Kafka’s default is murmur2(key) mod partitions.

    The animation follows three customers: cust-17 always lands on P1, cust-42 always on P0, cust-88 always on P2. Same key, same hash, same partition. Because a partition is an ordered log read by one consumer, all of one customer’s records are stored and processed in the order they were written.

    There is no order across partitions. Records without a key are spread over partitions by the producer (in batches, in current clients).

    The moving records are a scripted illustration; traffic is turned down to 15 records/s so you can follow them.

    Scene: Scripted records for three customers travel from the producers through the partitioner. cust-17 always goes to P1, cust-42 to P0 and cust-88 to P2. Background traffic is 15 records per second.

    Key idea: Same key → same partition → per-key order. The partition count is part of that mapping.

  4. 4. A hot key makes a hot partition

    Traffic is back to 75 records per second, but now one customer, a big marketplace seller, produces about 60% of all records, and a few others most of the rest.

    Every record of that key hashes to P1. P1 receives about 50 records per second, more than its consumer’s 40, and its lag grows. P2 is almost idle. The topic has spare capacity, just not where the traffic is.

    This is a hot partition. Throughput per key is capped at one partition’s, because per-key order needs one partition.

    Scene: One key produces about 60% of the records. It hashes to P1, whose backlog grows because its consumer cannot keep up. P0 is moderately busy and P2 is almost idle.

    Key idea: A skewed key concentrates load on one partition; the others cannot help, because a key never splits.

  5. 5. More partitions do not split a key

    The team adds P3 with its own consumer, hoping to spread the load.

    It does not help. The hot key still maps to one partition, here still P1, so P1’s lag keeps growing. P3 picks up only a few of the small keys and sits nearly idle.

    What does help: split the hot key itself (add a suffix such as seller-9#0…#7 and give up strict order across the suffixes, or order only per sub-entity such as per order instead of per seller), make the hot partition’s consumer faster (batching, cheaper processing), or route the heavy key to its own topic.

    Scene: A fourth partition, P3, and its consumer are added. The hot key still maps to P1, whose backlog keeps growing; P3 receives only a small share of records.

    Key idea: Adding partitions spreads keys, not a single key. Fix a hot key by changing the key or the work per record.

  6. 6. Changing the partition count moves keys

    Keys are even again. Look at the shares: P3 now takes about a fifth of the records, and every other partition got lighter. Those records belong to keys that used to live on another partition.

    In this simulation the partitioner is a hash ring, so only the keys P3 took over moved. Kafka’s default hash mod N is worse: going from 3 to 4 partitions moves about three quarters of all keys.

    The animation shows why that matters. cust-17’s older record (v4) is still waiting in P1’s backlog when its newer record (v5) goes to P3, whose consumer is idle. v5 is processed before v4: per-key order breaks across the change, and any per-key state a consumer kept (counts, sessions) is now on the wrong consumer.

    So choose the partition count up front with headroom, or drain producers before changing it.

    Scene: Keys are even again; P3 receives about a fifth of the records, taken from the other partitions. A scripted illustration shows cust-17’s older record waiting in P1 while its newer record goes to P3 and is processed first.

    Key idea: The key → partition mapping depends on the partition count. Changing it moves keys and can reorder a key’s records.

  7. 7. Choosing partitions

    A partition is the unit of parallelism (one consumer per group), of ordering (order holds inside it, never across) and of placement (each one lives on a broker and is replicated as a unit).

    Size the count from throughput: partitions ≥ peak records per second ÷ what one consumer handles, with headroom, because changing it later moves keys. Do not go to thousands "just in case": each partition costs broker memory, open files, replication traffic and longer leader elections.

    Choose keys that are even and match what must stay in order: the entity whose events must not be reordered, and nothing coarser.

    Scene: Four partitions, each with its own consumer, receive evenly keyed traffic of 75 records per second. All backlogs stay near empty.

    Key idea: Pick the key for ordering and spread, and the partition count for peak throughput with headroom.