Kafka partitions and groups

You can trace a keyed order event to its partition, so the relay sends every event for one order to the same place.

Learning outcomes

  • Explain how Kafka topics and partitions retain records and preserve order within a partition.
  • Trace how a record key routes every event for one order to the same partition.
  • Describe how consumer groups distribute partitions and use offsets to track progress.
  • Compare at-most-once, at-least-once and exactly-once delivery, including the effect of a crash.
  • Use franz-go to produce and consume records with the Redpanda broker.
Prerequisite conceptsIdempotency key

An order created and moved to PREPARING produces three order events: PLACED, ACCEPTED and PREPARING. The next exercise publishes those events from MySQL to Redpanda, and the notifier worker reads them later. You need to understand how Kafka preserves their order and what happens when a consumer crashes halfway through processing an event.

The broker in this course is Redpanda. Your Go services communicate with it using franz-go, a Kafka client library. Redpanda implements the Kafka protocol, so the same topics, partitions, consumer groups and offsets apply.

Topics as retained logs

Kafka stores records in an append-only log rather than handing each message to one worker and deleting it after acknowledgement.

A topic is a named stream of records. The order events in this course go to order-events. Producers append records to the topic, and consumers read them independently.

For example, the same topic can feed two services:

  • The notifier worker reads order events to create customer notifications.
  • An analytics service could read the same events to build reports.

Reading a record does not remove it. The broker retains records according to the topic's retention configuration. A consumer that falls behind can resume reading records that are still retained.

Each consumer group tracks its own position in the topic. One service therefore does not consume records on behalf of every other service.

Topics and partitions

A topic is divided into one or more partitions. Each partition is an ordered log. New records are appended to its end, and the broker assigns each record an offset within that partition.

This course uses three partitions for order-events:

bash
rpk topic create order-events -p 3

More partitions allow more consumers in one group to work concurrently. The trade-off is that Kafka guarantees ordering within a partition, not across the entire topic.

Suppose three order events are written to different partitions. A consumer can read them in a different overall order because there is no global ordering between partitions.

Record keys and partition selection

A Kafka record has a key and a value. The producer uses the key to select a partition. Records with the same key are routed to the same partition.

For order events, the key is the order ID represented as a decimal string:

go
key := []byte("42")

Every event belonging to order 42 uses that key. The broker therefore routes those events to the same partition, where their order is preserved.

Consider the events created when an order moves through its first two transitions:

json
[
  {"order_id":42,"from":"","to":"PLACED"},
  {"order_id":42,"from":"PLACED","to":"ACCEPTED"},
  {"order_id":42,"from":"ACCEPTED","to":"PREPARING"}
]

All three records carry the same order ID. They go to the same partition rather than being scattered across the topic.

Three partitions belonging to order-events. Events with the same order ID are routed to the same partition. Two members of the notifier consumer group share ownership of the three partitions.Three partitions belonging to order-events. Events with the same order ID are routed to the same partition. Two members of the notifier consumer group share ownership of the three partitions.

Consumer groups

A consumer group is a set of consumers sharing the work of reading a topic. Kafka assigns each partition to one member of a group at a time.

With three partitions and two members of the notifier group, one member owns two partitions and the other owns one.

With three partitions and five members, only three members can own partitions. The other two remain idle.

You can inspect the assignments with:

bash
rpk group describe notifier

Consumer groups are independent of each other. If notifier and analytics both consume order-events, each group receives every record and tracks its own progress.

Adding another instance with the same group ID distributes the existing group's partitions among more consumers. Giving an instance a different group ID creates an independent consumer group, which reads the topic separately.

This distinction matters for the product. You can run multiple notifier instances to share notification work without preventing analytics from seeing the same order events.

Offsets and progress

An offset is the position of a record within a partition. Each consumer group commits offsets to Kafka so it can resume from its last committed position after a restart or a rebalance.

A committed offset represents the next position from which the group should resume. For example, after processing the record at offset 7, the group commits offset 8.

A commit records progress. It does not prove that your application completed the work associated with the record.

A consumer reads the record at offset 7, performs its work, and commits offset 8. A crash before the commit causes the consumer group to read offset 7 again after restarting.A consumer reads the record at offset 7, performs its work, and commits offset 8. A crash before the commit causes the consumer group to read offset 7 again after restarting.

The order of processing and committing determines what happens after a crash.

  1. The consumer reads an event, performs the work and crashes before committing. Kafka still has the earlier committed offset, so the event can be delivered again.
  2. The consumer commits before performing the work and crashes during processing. The group resumes after the event, even though the work did not finish.

The first sequence can produce duplicates. The second can lose work.

Delivery guarantees

The timing of a consumer's offset commit determines its delivery guarantee.

At-most-once delivery commits progress before processing. A crash can cause unfinished work to be skipped. The consumer does not process that record again from the committed position.

At-least-once delivery processes the record before committing progress. A crash after processing but before committing can cause the same record to be delivered again. The consumer avoids skipping work that has not been committed.

Exactly-once delivery means the intended effect happens once despite retries. Achieving this across Kafka and an external database requires coordination between processing and recording progress. Choosing when to commit offsets alone does not provide that guarantee.

This course uses at-least-once delivery. Missing a customer notification because a worker crashed is worse than receiving the same event twice. You handle the duplicate in the consumer rather than risking lost work.

Idempotent processing

A consumer that receives an event twice should not apply its effect twice. For example, the notifier should not create two notification rows for the same order event.

The stable event_id gives the consumer an identifier for each event. The worker can record processed event IDs in MySQL and check them before applying an event again.

This is related to the API's Idempotency key. When a client retries an order request with the same idempotency key, the API can replay the stored response rather than creating another order. In both cases, a stable identifier lets the system recognise repeated work.

Redpanda and franz-go

Redpanda speaks the Kafka protocol. Your Go services can use franz-go without a separate Redpanda-specific client.

The local development environment exposes the Kafka API at 127.0.0.1:9092. The rpk CLI lets you inspect topics and consumer groups.

bash
rpk topic create order-events -p 3
rpk topic consume order-events -n 5
rpk group describe notifier

These commands create the topic, print the next five records and show the consumer group's progress.

The broker stores records. Your application decides what each record means and when it has completed the associated work.

Producing records with franz-go

The producer sends records to a topic. Each record carries a topic, a key and a value.

For an order event, the value is the event payload stored in the outbox row:

json
{
  "order_id": 42,
  "event_id": "<event-id>",
  "from": "PLACED",
  "to": "ACCEPTED"
}

The order_id identifies the order, while event_id identifies the particular event. The from and to fields describe the transition.

A franz-go producer connects to the broker using kgo.NewClient:

go
cl, err := kgo.NewClient(
    kgo.SeedBrokers("127.0.0.1:9092"),
)
if err != nil {
    return err
}
defer cl.Close()

To publish a record, use ProduceSync:

go
record := &kgo.Record{
    Topic: "order-events",
    Key:   []byte("42"),
    Value: payload,
}

if err := cl.ProduceSync(ctx, record).FirstErr(); err != nil {
    return err
}

ProduceSync waits for the broker to acknowledge the record. FirstErr reports the first publication error.

A successful result means the broker accepted the record. It does not mean that the notifier has processed it or that a notification has been stored in MySQL.

Consuming records with franz-go

The notifier joins a consumer group and subscribes to order-events. You disable automatic commits so the application controls when it records progress.

go
cl, err := kgo.NewClient(
    kgo.SeedBrokers("127.0.0.1:9092"),
    kgo.ConsumerGroup("notifier"),
    kgo.ConsumeTopics("order-events"),
    kgo.DisableAutoCommit(),
)
if err != nil {
    return err
}
defer cl.Close()

The consumer polls for records and processes them before committing offsets:

go
fetches := cl.PollFetches(ctx)
if ctx.Err() != nil || fetches.IsClientClosed() {
    return nil
}

fetches.EachRecord(func(r *kgo.Record) {
    handle(ctx, r)
})

The processing step must succeed before the corresponding progress is committed. For production handling, check processing errors and leave failed work uncommitted so it can be retried.

After successful processing, the consumer can commit its uncommitted offsets:

go
if err := cl.CommitUncommittedOffsets(ctx); err != nil {
    slog.Error("commit offsets", "err", err)
}

The commit happens after the work, not before it. That is the ordering required for at-least-once delivery.

The simple example does not yet cover failed-record handling, retries or durable deduplication. The notifier exercise adds those behaviours, including the retry topic and dead-letter topic.

The producer and the outbox relay

The API already writes an order change and its outbox row in one MySQL transaction. The outbox gives the system a durable record to publish, even when Kafka is temporarily unavailable.

The outbox relay is the producer for this stream. It reads committed outbox rows and publishes records to their stored topics. For order events, the decimal order ID is the key, and the outbox payload supplies the record value.

There is an important failure window. Kafka can acknowledge a record before MySQL commits the update that marks its outbox row as sent. If the API process crashes during that window, the relay can publish the same event again after restarting.

That is why the relay and notifier use different forms of progress tracking. The relay tracks publication with sent_at in MySQL. The notifier tracks consumption with Kafka offsets and durable event processing records.

The exercise, Outbox relay to order-events, connects these pieces. Its tests check that the three transitions for an order reach order-events in order within 15 seconds, using the decimal order ID as the key. They also check that sent rows are not published again, that rows reach their stored topics in ascending outbox ID order and that a locked row does not block later unlocked rows.

Check your understanding

Question 1 of 4

An order produces three events with order ID 42. Why should all three records use []byte("42") as their Kafka key?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Redpanda (Kafka API), franz-go v1.22).

Finished Lesson 3.13?