Skip to content
Visual explainer 6h to learn 6 steps

Messaging with Kafka

Produce and consume events and understand partitions and consumer groups.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 25 of 29

In short

Kafka is a distributed log for events. Producers append events to topics, which are split into partitions, and consumer groups read them independently at their own pace using offsets.

Explained simply

Kafka is a system for passing events between services. An event is a small record of something that happened, like "order 7 was placed". One service writes it, and any number of other services can read it later, each at its own speed. The writer does not need to know who the readers are.

Picture a shared notebook where people only add new lines at the end. Nobody tears out pages. Each reader keeps a bookmark (an offset) showing how far they have read. Billing may be on line 500 while the email service is on line 480. That notebook is a topic.

One notebook would be too slow for a big system, so a topic is split into partitions: several notebooks that are read and written in parallel. Events with the same key, such as the same order id, always go to the same partition, so their order is kept.

Readers work in teams called consumer groups. Kafka hands each partition to exactly one member of a team, so the work is shared without two members handling the same event. Add members to go faster, up to one per partition. Different teams each get their own full copy of the stream.

Press Play on a diagram to walk through it one step at a time.

SequenceProducer, broker, consumer
Producer
Kafka broker
Consumer (group billing)
  1. 1send orders, key=order-7
    Producer to Kafka broker: send orders, key=order-7
  2. 2ack: partition 2, offset 41
    Kafka broker to Producer: ack: partition 2, offset 41
  3. 3poll partition 2
    Consumer (group billing) to Kafka broker: poll partition 2
  4. 4records from offset 41
    Kafka broker to Consumer (group billing): records from offset 41
  5. 5commit offset 42 after processing
    Consumer (group billing) to Kafka broker: commit offset 42 after processing
MapTopic and consumer group
Topic: orders
  • Partition 0
    • Consumer A reads it
  • Partition 1
    • Consumer A reads it
  • Partition 2
    • Consumer B reads it
MapTwo groups reading the same topic
Topic orders (3 partitions)
  • Group billing
    • Consumer 1: partitions 0 and 1
    • Consumer 2: partition 2
    • Own offsets per partition
  • Group email
    • Consumer 1: partitions 0, 1 and 2
    • Reads at its own pace
    • Lag does not affect billing

In depth

Topics, partitions and offsets under the hood

Each partition is an append-only log stored on a broker (a Kafka server). New records get the next offset number in that partition: 0, 1, 2 and so on. Offsets are only meaningful inside one partition, so there is no global order across a topic.

Kafka does not delete a record when it is read. Records stay until the retention limit, which is 7 days by default (log.retention.hours=168), or until a size limit is reached. That is why a new consumer group can replay a whole week of history, and why a bug fix can be followed by reprocessing old events.

For safety each partition is copied to several brokers. The replication factor says how many copies exist; one copy is the leader that handles reads and writes, and the others follow. With acks=all, a write is only confirmed once the in-sync replicas have it, controlled by min.insync.replicas.

  • Same key means same partition, so per-key order is kept
  • A null key spreads records across partitions
  • You can add partitions later, but never remove them
  • Adding partitions changes which partition a key maps to

Running Kafka locally

Kafka 4.0 removed ZooKeeper completely. Brokers now manage their own metadata with KRaft (Kafka Raft), so one container is enough for local work. The official apache/kafka image starts a single-node broker listening on port 9092 with sensible defaults.

The command-line tools live in /opt/kafka/bin inside that image. You can create a topic with a chosen number of partitions, send test records, and, most usefully, describe a consumer group to see each partition's current offset, the latest offset, and the lag between them. Lag is the number of records waiting to be processed, and it is the first metric to watch in production.

In Spring Boot, point the app at the broker with spring.kafka.bootstrap-servers=localhost:9092. When the app itself runs in Compose, use the service name instead of localhost, and make sure the broker advertises an address the app can reach.

Producing and consuming with Spring Kafka

KafkaTemplate.send(topic, key, value) is asynchronous: it returns a CompletableFuture that completes when the broker acknowledges the record. Since Kafka 3.0 the producer defaults to acks=all with idempotence turned on, so a retry after a network glitch does not write duplicates into the partition.

@KafkaListener creates a listener container that polls the broker in a loop and calls your method for each record. Spring turns off the client's automatic offset commit and commits offsets itself after your method returns (by default once per polled batch). If your code throws, the offset is not committed and the record is delivered again. This gives at-least-once delivery: no record is lost, but a record may be processed twice, so handlers must be idempotent.

Configure JSON with spring.kafka.producer.value-serializer and the matching consumer deserializer, plus spring.json.trusted.packages for the classes you accept.

SequenceA failed record being redelivered
Listener
Spring container
Broker
  1. 1poll: records 41 to 45
    Spring container to Broker: poll: records 41 to 45
  2. 2record 41
    Spring container to Listener: record 41
  3. 3throws exception
    Listener to Spring container: throws exception
  4. 4seek back to offset 41
    Spring container to Broker: seek back to offset 41
  5. 5record 41 again (retry)
    Spring container to Listener: record 41 again (retry)
  6. 6success
    Listener to Spring container: success
  7. 7commit offset 42
    Spring container to Broker: commit offset 42

Retries and dead-letter topics

Some failures are temporary (the database blinked) and some are permanent (the JSON is broken). Spring Kafka's DefaultErrorHandler retries a failing record in place, by default up to 9 more times with no pause, then logs it and moves on. Give it a backoff and a recoverer instead: a DeadLetterPublishingRecoverer sends the record to a dead-letter topic, by default the original name plus .DLT, with headers that describe the exception.

Retrying in place blocks the partition, because later records wait behind the failing one. For slow retries, @RetryableTopic sends the record to separate retry topics with growing delays and finally to a -dlt topic, so the main topic keeps flowing.

Mark exceptions that will never succeed, such as validation errors, as not retryable so they go straight to the dead-letter topic. Then monitor that topic: messages there are real problems someone must look at.

  • Blocking retries keep order but stall the partition
  • Retry topics keep flowing but give up strict ordering
  • Store a processed event id to make handlers idempotent

Scaling with consumer groups

Within one group, each partition is assigned to exactly one consumer. With 6 partitions and 3 consumers, each gets 2. Add a fourth and Kafka rebalances, moving partitions so the load evens out. Add a seventh and it sits idle. So the partition count is the ceiling on parallelism for one group; choose it with growth in mind.

A rebalance also happens when a consumer crashes or takes too long between polls (max.poll.interval.ms, 5 minutes by default). Slow handlers can therefore cause endless rebalances: process faster, poll fewer records (max.poll.records, default 500), or move heavy work elsewhere.

When a group starts with no saved offsets, auto.offset.reset decides where to begin: latest (the default) skips old records, earliest reads from the start of retention.

Learn it in 6 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Learn topics, partitions and offsets~1h
  2. 2
    Run Kafka locally with Docker~1h
  3. 3
    Produce events with KafkaTemplate~1h
  4. 4
    Consume events with @KafkaListener~1h
  5. 5
    Scale with consumer groups~1h
  6. 6
    Handle retries and dead-letter topics~1h

Key points

  • Events with the same key go to the same partition, so their order is kept.
  • Within a group, each partition is read by one consumer; more consumers than partitions sit idle.
  • Consumers commit offsets to remember progress; delivery is usually at-least-once.
  • Make handlers idempotent and send poison messages to a dead-letter topic.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@Service
class OrderEvents {
  private final KafkaTemplate<String, OrderPlaced> kafka;
  OrderEvents(KafkaTemplate<String, OrderPlaced> kafka) { this.kafka = kafka; }

  void publish(OrderPlaced e) {
    kafka.send("orders", e.orderId(), e);  // same key, same partition
  }

  @KafkaListener(topics = "orders", groupId = "billing")
  void onOrder(OrderPlaced e) {
    System.out.println("Billing order " + e.orderId());
  }
}

Create a topic and watch consumer lag

Start a single-node broker, create an orders topic with 3 partitions, send a few keyed records, then read them as group billing. Describe the group afterwards: CURRENT-OFFSET is what the group committed, LOG-END-OFFSET is the newest record, and LAG is the difference.

bash
docker run -d --name kafka -p 9092:9092 apache/kafka:4.0.0
K=/opt/kafka/bin
docker exec kafka $K/kafka-topics.sh --bootstrap-server localhost:9092 \
  --create --topic orders --partitions 3
docker exec -it kafka $K/kafka-console-producer.sh --bootstrap-server localhost:9092 \
  --topic orders --property parse.key=true --property key.separator=:
# type: order-7:placed   order-7:paid   then Ctrl+D
docker exec kafka $K/kafka-console-consumer.sh --bootstrap-server localhost:9092 \
  --topic orders --group billing --from-beginning --max-messages 2
docker exec kafka $K/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
  --describe --group billing

Retry with backoff, then dead-letter

Billing sometimes fails because a payment service is down. Step 1: define a DefaultErrorHandler bean with an exponential backoff, so a record is retried a few times with growing pauses. Step 2: give it a DeadLetterPublishingRecoverer so a record that still fails lands in orders.DLT. Step 3: mark validation errors as not retryable. Spring Boot picks up the error handler bean for its listener containers.

java
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
  var recoverer = new DeadLetterPublishingRecoverer(template);
  var backoff = new ExponentialBackOffWithMaxRetries(4);
  backoff.setInitialInterval(1_000);
  backoff.setMultiplier(2.0);
  var handler = new DefaultErrorHandler(recoverer, backoff);
  handler.addNotRetryableExceptions(IllegalArgumentException.class);
  return handler;
}

Quick reference

  • Kafka 4.x runs without ZooKeeper (KRaft mode); the usual client port is 9092
  • Order is guaranteed only inside one partition, so key events by entity id
  • Max useful consumers in one group = number of partitions
  • kafka-consumer-groups.sh --describe --group g shows offsets and lag
  • Default retention is 7 days; reading a record does not delete it
  • auto.offset.reset=earliest makes a new group start from the oldest kept record
  • Delivery is at-least-once by default: make every handler idempotent
  • DeadLetterPublishingRecoverer sends failed records to topic.DLT by default

Common mistakes

  • Assuming global ordering across partitions; order holds only within one.
  • Non-idempotent consumers that double-charge on redelivery.
  • Retrying a bad message forever and blocking the partition.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A topic has 4 partitions. How many consumers in one group can actively read it at the same time?

Question 2

2Your listener throws an exception and no error handler is customised. What happens by default in Spring Kafka?

Question 3

3Why should Kafka consumers be idempotent?

Question 4

4A new consumer group starts with auto.offset.reset left at its default. Which records does it read?

Question 5

5Your handler sometimes takes 10 minutes per batch and the group keeps rebalancing. What is the most likely cause?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a topic with 3 partitions, send records with keys a, b and c several times each, and confirm that each key always lands in the same partition.

  2. Exercise 2medium

    Write a @KafkaListener for an orders topic that ignores an order it has already processed, so a redelivery does not bill twice.

  3. Exercise 3hard

    Switch the listener to non-blocking retries: three attempts with 2, 4 and 8 second delays, then a dead-letter topic, while the main topic keeps flowing.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Kafka or RabbitMQ?
Kafka is a durable log that many groups can replay, which suits event streams and high volume. RabbitMQ is a classic message broker with flexible routing where a message is usually removed once consumed.
Does Kafka guarantee exactly-once delivery?
Kafka supports exactly-once for read, process and write cycles that stay inside Kafka, using transactions. Side effects outside Kafka, like a database write or an email, still need idempotent handling.
How many partitions should a topic have?
Enough for the parallelism you expect, since consumers in a group cannot exceed it. A few to a few dozen is common; adding later is possible but reshuffles which partition each key uses.
Do I still need ZooKeeper?
No. Kafka 4.0 dropped ZooKeeper, and new clusters run in KRaft mode where brokers manage their own metadata.

Go deeper

ShareXLinkedInWhatsApp