Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Architecture and operations › Messaging and asynchronous processing

Kafka partitions and consumers

I added consumers, so why is the throughput the same?

Why it exists — In an ordinary message queue, the consumer deletes a message once it is processed, so it is hard for another system to read the same message again, and attaching several consumers mixes up the processing order. Kafka divides a topic into several partitions, keeps the order within each partition while consumers divide the reading among themselves, and does not delete a message just because it was read, so that each consumer group can read separately.

Where it's used today — It is used in structures where one order event is received and processed by the payment, shipping, and notification services separately, and where records that pile up many per second, such as clicks and logs, are collected. Messages whose order matters, such as events of the same order, are sent to the same partition with the same key. When there are few messages and only task distribution is needed, a queue such as RabbitMQ is sometimes used.

A topic is split into partitions, and the consumers of a consumer group divide the partitions among themselves. Within a group, a partition can be read by only one consumer.

Checked against real execution · All 324 combinations were run on Apache Kafka 4.1.1 (Docker apache/kafka:4.1.1) with kafka-clients 4.2.1 and checked (time converted to counts, default assignor range)

Concepts in this lab

Kafka topics, partitions, and offsets
A topic is a name that separates messages by kind. A topic is divided into one or more partitions, and a partition is a record (log) to which messages are appended at the end in the order they arrive. An offset is a number that shows the position of each message within a partition, and a consumer uses offsets to record how far it has read. Order is guaranteed only within the same partition.
Consumer groups and rebalancing
Why it exists — If you only add more consumers reading the same topic, several consumers may process the same message twice. A consumer group assigns the partitions among the consumers in the group, so that even when you add consumers to raise throughput, normally only one consumer in the group processes each message.
Where it's used today — When you run several servers that process order events, you give them the same group.id to divide the work, and services that must each receive the same event, such as settlement and notification, get different group.id values. If there are more consumers than partitions, the extra consumers sit idle.
A consumer group is a set of consumers that share the work of processing one topic. Within the group, each partition is assigned to only one consumer, so the consumers divide the messages among them. Rebalancing is the process of dividing up the partition assignments again when a consumer is added or stops, and processing can be delayed briefly while it is in progress.
Consumer lag
The difference between the position of the last message that producers wrote and the position that the consumer has processed. In other words, it is the amount of messages that are piled up and not yet processed. If the value keeps growing, the consuming speed is not keeping up with the producing speed.
Message delivery guarantees
The level of guarantee about how many times a message is delivered. With at-most-once, a message is delivered at most one time, so there are no duplicates but messages can be lost. With at-least-once, a message is delivered at least one time, so nothing is lost but duplicates can occur. With exactly-once, a message is delivered exactly one time. In practice, systems often use at-least-once and make the consumer handle duplicates (idempotent).
Message queue
An intermediate store that sits between the sending side (the producer) and the receiving side (the consumer), holds messages, and then delivers them. The producer puts a message in and moves straight on to its next work, and the consumer takes messages out and processes them at its own pace. The two systems do not call each other directly, so coupling is lower, and a sudden burst of requests can be piled up and processed later.
Idempotency and idempotency keys
Where it's used today — In payment approval, money transfer, and order creation APIs, the client sends a key in a header such as Idempotency-Key, and the server records that key using a database unique key or Redis and filters out requests with the same key. Message consumers also use it to filter out duplicates.
Idempotency is the property that performing the same request several times gives the same result as performing it once. A network problem can cause the same request to be sent again, so operations that must not be duplicated, such as payments, must be made idempotent. An idempotency key is a unique value that the client attaches to each request. When a request arrives with a key that the server has already processed, the server does not process it again and returns the earlier result.

Try these

Running with the default settings

  1. 2 consumers subscribe to the topic as one group. The 3 partitions are divided among the consumers (the group coordinator coordinates the assignment). The assignor of this run (RangeAssignor, the default of kafka-clients) groups the partitions in number order and hands them out starting with consumer 1. Within a group, a partition is handled by only one consumer.
  2. Messages arrive at 120 per second, and 40 per second go into each partition (assuming each partition receives the same amount). Each consumer processes 50 messages per second, and its capacity stays the same even when it handles several partitions. A consumer whose partitions together receive more than 50 per second falls behind by the excess. The throughput of the whole group is 90 messages per second.
  3. 10 seconds have passed. Processing cannot keep up with the inflow, so 300 messages are waiting unread (consumer lag). If this continues, the lag grows without limit.

Result of this run

Code

// Only the lines inside a method are shown (consumer setup, the example Order and handle declarations, class, and imports omitted)
// Topic orders: 3 partitions
// Consumer group order-service: 2 consumers

while (true) {
    ConsumerRecords<String, Order> records = consumer.poll(Duration.ofMillis(500));
    for (var r : records) {
        handle(r.value());               // first, process
    }
    consumer.commitSync();               // then, record "read up to here"
}

Assumptions of this model

All 324 combinations (1, 3, and 6 partitions, 1, 2, and 6 consumers, an inflow of 30, 120, and 300 per second, processing of 10, 50, and 100 per second, 2 commit timings, with and without a failure) were run on a real Kafka and checked. The broker is Apache Kafka 4.1.1 (the Docker image apache/kafka:4.1.1, 1 broker, only inside 127.0.0.1 of this computer), the client is kafka-clients 4.2.1, and the JDK is 21.0.12.1. Time was converted to counts so that every run gives the same numbers. "r messages per second arrive for 10 seconds" was done by putting r×10 messages into the topic, the same number in each partition (the producer gives the partition number directly), and "one consumer processes k messages per second" was done by letting each consumer process up to k×10 messages and then stop. So the throughput per second is the number of messages the consumers really processed divided by 10, and the messages waiting are the sum of the end offset minus the committed offset that the broker held at that moment. The loop of the consumer has the same shape as the code on the screen (poll, handle, commitSync), and the settings are enable.auto.commit=false, auto.offset.reset=earliest, max.poll.records=5 (one poll returns 5 records), session.timeout.ms=6000, and heartbeat.interval.ms=1500, with the rest left at the defaults. The partition assignment is the result that came out of the default settings of kafka-clients 4.2.1 (group.protocol=classic, and the assignor name the broker reported is range). This assignor grouped the partitions in number order and handed them out starting with the consumer whose client.id comes first (with 3 partitions and 2 consumers, consumer 1 gets partitions 0 and 1, and consumer 2 gets partition 2). If you change the assignor (for example CooperativeStickyAssignor) or use the new consumer group protocol (group.protocol=consumer), which consumer handles which partition and how much stops during a rebalance can be different, and those cases were not run. How the capacity of a consumer that handles several partitions is divided among them depends on the order in which messages are fetched, so the screen shows only the totals per consumer. In this run the messages were put in beforehand, so the partition with the lower number was emptied first. In the failure combinations, consumer 1 ran as a separate Java process, fetched 5 records, and the process was ended as it was right after it processed the third one (no close, and no request to leave the group). After that it was checked that the committed offset on the broker was the start of the 5 fetched records with commit after processing, and right after the 5 records with commit before processing. The broker removed that consumer from the group and finished rebalancing 3.7 to 7.2 seconds later (this run reduced session.timeout.ms from the default of 45 seconds to 6 seconds, and this time changes on every run). At that time the remaining consumers gave up all the partitions they were handling and were assigned again (checked with onPartitionsRevoked of ConsumerRebalanceListener). The first offset that the consumer taking over processed on that partition was the same as the committed position, and after the consumers were made to process everything that was waiting, all the handle records were counted, which confirmed 3 duplicates (the first three) with commit after processing and 2 lost messages (the last two) with commit before processing. The throughput and the amount waiting after the reassignment were checked against values measured by first emptying everything that was waiting and then putting in another 10 seconds of messages with the new assignment. In the failure combinations with only one consumer, it was checked that the group becomes empty, that the lag grew by exactly the amount of another 10 seconds of messages, and that a consumer started again read from the committed position. The time a rebalance takes and the delay during it are not given as numbers on the screen. It was also checked by running that the processing order within a partition was the same as the offset order, that trying to reduce the partitions from 3 to 2 raises InvalidPartitionsException while increasing them to 6 works, and that messages with the same key go to the same partition and, when the partitions were increased from 3 to 6, the partition changed for 6 of 10 keys. That messages remain for the retention period and the names of the delivery guarantees (at-least-once, at-most-once) follow the official Kafka documentation. The check is done by verify/net/cmp_kafka.js.

Previous lab: Message queue basics · Next lab: Circuit breaker

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these