Vladyslav Krylasov's website

Scaling Kafka: topic-level parallel message processing in Go

Published on

Contents

Context

We started with a Kafka topic that had one partition and one service instance processing its messages. That worked until we had to run the service as several replicas.

With one partition, more consumers (one per replica) didn’t raise throughput. Kafka gives each partition to only one consumer in a consumer group, so the extra consumers sat idle. To process messages in parallel, we needed more partitions, so each consumer could get its own.

We also didn’t want to assign, reassign, or rebalance partitions by hand as replicas came and went. Kafka’s consumer groups already do this. Kafka spreads the partitions across the consumers in a group and moves them when a consumer joins or leaves.

Solution

We start several consumers in the same consumer group, each in its own goroutine, and set the partition assignment strategy to round-robin. Kafka splits the partitions evenly between those consumers, so messages get processed in parallel with no custom coordination code.

Example setup

The code for this article is in this repository1.

Docker Compose

This Docker Compose file starts Kafka, ZooKeeper, and Kafka UI locally.

services:
  kafka-ui:
    image: provectuslabs/kafka-ui:latest
    container_name: kafka-ui
    ports:
      - 8080:8080
    environment:
      - KAFKA_CLUSTERS_0_NAME=local
      - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=kafka:9092
      - KAFKA_CLUSTERS_0_ZOOKEEPER=zookeeper:2181
    depends_on:
      - kafka
      - zookeeper
    networks:
      - net

  zookeeper:
    image: confluentinc/cp-zookeeper:7.9.2
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - 2181:2181
    networks:
      - net

  kafka:
    image: confluentinc/cp-kafka:7.9.2
    depends_on:
      - zookeeper
    ports:
      - 9092:9092
      - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    healthcheck:
      test:
        ["CMD", "kafka-topics", "--bootstrap-server", "kafka:9092", "--list"]
      interval: 5s
      timeout: 5s
      retries: 5
    networks:
      - net

networks:
  net:

Run it with docker-compose up --build -d.

Go

The service is in Go and talks to Kafka through confluent-kafka-go.

Modules

go.mod sets the module path and the dependencies.

module github.com/sprytnyk/kafka-topics-scaling

go 1.24.4

require (
	github.com/confluentinc/confluent-kafka-go v1.9.2
	github.com/sirupsen/logrus v1.9.3
)

require golang.org/x/sys v0.12.0 // indirect

Consumers

The code does five things:

  1. It creates the topic if it’s missing. Before consuming, it checks whether the topic exists. If not, it creates it through the Kafka AdminClient with the given number of partitions and replication factor.
  2. It starts two consumers in the same consumer group, each in its own goroutine. With the round-robin strategy, Kafka splits the partitions evenly between them.
  3. It handles rebalances. rebalanceCallback takes the partitions Kafka assigns and drops the ones Kafka revokes, as consumers join or leave the group.
  4. It polls for messages and commits each offset by hand after processing. If the committed offset isn’t the message offset plus one, it logs a mismatch, which helps catch delivery or commit problems.
  5. It shuts down cleanly. On SIGINT or SIGTERM, it cancels the context, waits for every consumer to exit, and then stops.
package main

import (
    "context"
    "os/signal"
    "sync"
    "syscall"
    "time"

    "github.com/confluentinc/confluent-kafka-go/kafka"
    log "github.com/sirupsen/logrus"
)

func init() {
    log.SetFormatter(&log.TextFormatter{
        FullTimestamp:   true,
        TimestampFormat: "2006-01-02 15:04:05",
    })
}

func createTopic(
    admin *kafka.AdminClient,
    topic string,
    numPartitions int,
    replicationFactor int,
) {
    metadata, err := admin.GetMetadata(nil, true, 10_000)
    if err != nil {
        log.WithError(err).Error("Failed to fetch metadata")
        return
    }

    if _, exists := metadata.Topics[topic]; exists {
        log.Infof(
            "Topic '%s' already exists. Skipping creation.",
            topic,
        )
        return
    }

    ctx, cancel := context.WithTimeout(
        context.Background(),
        10*time.Second,
    )
    defer cancel()

    results, err := admin.CreateTopics(
        ctx,
        []kafka.TopicSpecification{{
            Topic:             topic,
            NumPartitions:     numPartitions,
            ReplicationFactor: replicationFactor,
        }},
    )
    if err != nil {
        log.WithError(err).Error("Failed to create topic")
        return
    }

    for _, result := range results {
        if result.Error.Code() != kafka.ErrNoError {
            log.WithFields(log.Fields{
                "topic": result.Topic,
                "error": result.Error,
            }).Error("Topic creation failed")
        } else {
            log.Infof(
                "Topic '%s' created successfully",
                result.Topic,
            )
        }
    }
}

func rebalanceCallback(
    c *kafka.Consumer,
    event kafka.Event,
) error {
    switch e := event.(type) {
    case kafka.AssignedPartitions:
        log.WithField(
            "partitions",
            e.Partitions,
        ).Info("Partitions assigned.")
        return c.Assign(e.Partitions)
    case kafka.RevokedPartitions:
        log.WithField(
            "partitions",
            e.Partitions,
        ).Info("Partitions revoked.")
        return c.Unassign()
    default:
        log.Infof("Unknown rebalance event: %v", e)
        return nil
    }
}

func runConsumer(
    ctx context.Context,
    wg *sync.WaitGroup,
    config *kafka.ConfigMap,
    topics []string,
    i int,
) {
    defer wg.Done()

    c, err := kafka.NewConsumer(config)
    if err != nil {
        log.WithError(err).Error("Failed to create consumer")
        return
    }
    defer c.Close()

    if err := c.SubscribeTopics(
        topics,
        rebalanceCallback,
    ); err != nil {
        log.WithError(err).Error("Failed to subscribe to topics")
        return
    }

    log.Infof("Consumer %d is polling for messages...", i)

    for {
        select {
        case <-ctx.Done():
            log.Infof("Consumer %d exiting...", i)
            return
        default:
            ev := c.Poll(2000)
            if msg, ok := ev.(*kafka.Message); ok {
                offsets, err := c.CommitMessage(msg)
                currentOffset := int64(msg.TopicPartition.Offset)
                commitOffset := int64(0)
                if len(offsets) > 0 {
                    commitOffset = int64(offsets[0].Offset)
                }
                if !(commitOffset-1 == currentOffset) {
                    log.WithFields(log.Fields{
                        "currentOffset": currentOffset,
                        "commitOffset":  commitOffset,
                        "offsets":       offsets,
                        "msg":           msg,
                    }).Error("Kafka offset mismatch.")
                }

                if err != nil {
                    log.Errorf(
                        "Fault commit consumer: (offsets: %v), {%v}",
                        offsets,
                        err,
                    )
                    return
                } else {
                    log.WithFields(log.Fields{
                        "currentOffset": currentOffset,
                        "commitOffset":  commitOffset,
                        "offsets":       offsets,
                        "msg":           msg,
                    }).Info("Kafka offset update.")
                }
            }
        }
    }
}

func initConsumers(
    ctx context.Context,
    wg *sync.WaitGroup,
    config *kafka.ConfigMap,
) {
    consumers := 2
    for i := range consumers {
        wg.Add(1)
        go runConsumer(ctx, wg, config, []string{"dummy"}, i)
    }
}

func main() {
    adminCfg := &kafka.ConfigMap{
        "bootstrap.servers": "localhost:29092",
    }

    admin, err := kafka.NewAdminClient(adminCfg)
    if err != nil {
        log.WithError(err).Fatal("Failed to create AdminClient")
    }
    defer admin.Close()

    createTopic(admin, "dummy", 10, 1)

    consumerCfg := &kafka.ConfigMap{
        "bootstrap.servers":               "localhost:29092",
        "group.id":                        "go-poc",
        "auto.offset.reset":               "earliest",
        "partition.assignment.strategy":   "roundrobin",
        "connections.max.idle.ms":         1800000,
        "go.application.rebalance.enable": true,
        "go.logs.channel.enable":          true,
        "enable.auto.commit":              false,
    }

    var wg sync.WaitGroup
    ctx, stop := signal.NotifyContext(
        context.Background(),
        syscall.SIGINT,
        syscall.SIGTERM,
    )
    defer stop()

    go initConsumers(ctx, &wg, consumerCfg)

    <-ctx.Done()
    log.Info("Shutdown signal received")

    wg.Wait()
    log.Info("All consumers shut down cleanly")
}

Running

Now run the code and watch Kafka assign and rebalance partitions.

Step 1. Run one replica.

Start one instance of the service. Kafka assigns all partitions to its two consumers, and they start processing messages.

$ go run main.go
Two consumers of Replica 1 take 10 partitions
Two consumers of Replica 1 take 10 partitions
Kafka consumer group shows 2 consumers in a group
Kafka consumer group shows 2 consumers in a group

Step 2. Run a second replica.

To add a second replica to the consumer group, open a new terminal tab and run the same command:

$ go run main.go

Then:

  • Kafka sees a new consumer join the group
  • Kafka starts a rebalance
  • Kafka splits the 10 partitions between the two replicas, 5 each

In the logs, you’ll see:

  • Replica 1 loses some partitions
  • consumers in both replicas get new assignments
Replica 2’s two consumers take 5 partitions, and Replica 1 loses 5
Replica 2’s two consumers take 5 partitions, and Replica 1 loses 5
Kafka consumer group shows 4 consumers in a group
Kafka consumer group shows 4 consumers in a group

Step 3. Stop the second replica.

Press Ctrl+C in the second replica’s terminal so its consumers leave the group.

Then:

  • Kafka sees the second replica leave
  • Kafka starts another rebalance
  • Replica 1 gets back the 5 partitions it lost
Replica 1 reclaims 10 partitions
Replica 1 reclaims 10 partitions
Kafka consumer group shows 2 consumers in a group
Kafka consumer group shows 2 consumers in a group

As replicas join and leave, Kafka keeps every partition assigned to a consumer.

Summary

With Kafka’s consumer groups, you get:

  • partitions processed in parallel
  • scaling by adding or removing replicas
  • partition assignment and rebalancing done by Kafka, with no partition-to-consumer mapping to maintain