Skip to content

Connecting and Using Kafka with Golang ​

Connect to the local Kafka from Golang and use its common features one by one: connection and configuration, producing messages, direct partition reads, consumer groups and offset commits, topic administration, lag queries, and finally a one-command end-to-end regression.

The runnable project lives in the repository at docs/public/demos/kafka: every capability is one subcommand (built on sarama and cobra) and one make target, each runnable and observable on its own. Read the project for the full code; the sections here only carry the short snippets needed to understand the usage.

The default assumption is a cluster already started via Running Kafka Locally (make kafka-up until healthy). All commands below run inside docs/public/demos/kafka.

Prerequisites ​

ItemRequirement
KafkaStarted via Running Kafka Locally; make kafka-status shows healthy
Go1.27.4 (the version declared in the project's go.mod)
Dependenciesgithub.com/IBM/sarama v1.60.2, github.com/spf13/cobra v1.10.2

If Go is not installed yet, on macOS use Homebrew:

bash
brew install go
go version

On Linux download the official binary archive (same version as the table above):

bash
GO_VERSION=1.27.4
ARCH=$(uname -m | sed 's/x86_64/amd64/; s/aarch64/arm64/')
curl -Lo go.tgz "https://go.dev/dl/go${GO_VERSION}.linux-${ARCH}.tar.gz"
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go.tgz
export PATH="/usr/local/go/bin:${PATH}"
go version

The PATH change must go into ~/.bashrc or ~/.zshrc to survive new terminals. Fetch dependencies and compile; no output means success:

bash
git clone https://github.com/zq-xu/zq-xu.github.io.git
cd zq-xu.github.io/docs/public/demos/kafka

go mod download
go build ./...

Connection and configuration ​

A connection needs exactly two things: the broker address and a sarama.Config. The local cluster listens on localhost:9092 (its KAFKA_ADVERTISED_LISTENERS); four reliability settings in the config should be on by default:

go
cfg := sarama.NewConfig()
cfg.Version = sarama.V3_9_0_0                 // align with the broker version
cfg.Producer.RequiredAcks = sarama.WaitForAll // leader + all in-sync replicas
cfg.Producer.Idempotent = true                // dedupe retries by producer id + sequence
cfg.Net.MaxOpenRequests = 1                   // hard requirement of the idempotent producer
cfg.Consumer.Offsets.Initial = sarama.OffsetOldest

The full template is in internal/kafkax/config.go. What the four values mean:

SettingValueWhy
VersionV3_9_0_0Matches broker 3.9.1; an older version silently downgrades the protocol
RequiredAcksWaitForAllReturns only after all in-sync replicas persist the record; a single replica crash loses nothing
Idempotenttrue (with MaxOpenRequests=1)Retries never duplicate records; MaxOpenRequests=1 is a hard requirement of idempotence
Offsets.InitialOffsetOldestA group without commits reads from the earliest record, convenient for local debugging

sarama.NewClient opens the connection (discovers brokers, pulls metadata, subscribes to nothing); management operations then derive a sarama.ClusterAdmin from that client.

Check connectivity with make health; expect the broker count, the controller and the metadata refresh duration:

bash
make health
text
== Cluster health ==
  client addresses   : localhost:9092
  metadata refresh   : OK (4ms)
  brokers            : 1
  controller         : broker#1 localhost:9092

sarama connects lazily: Broker.Connected() stays false until the first request, so printing it misjudges connectivity. Trust a successful metadata refresh instead.

Producing messages ​

Two things matter on the produce side: the record really lands on disk (only a broker-returned partition + offset proves it), and the key-to-partition mapping is stable (the premise of per-partition ordering).

Synchronous produce waits for the ACK of every record and returns its real landing spot. make produce sends 10 small records synchronously; expect each record's partition and offset to be printed:

bash
make produce

The core code is only a few lines — the message carries a key and headers (source, seq), and sync mode gets the broker receipt:

go
msg := &sarama.ProducerMessage{
    Topic: topic,
    Key:   sarama.StringEncoder(key),
    Value: sarama.ByteEncoder(body),
    Headers: []sarama.RecordHeader{
        {Key: []byte("source"), Value: []byte("kafka-demo")},
    },
}
partition, offset, err := producer.SendMessage(msg) // broker-confirmed

In the output the same key always lands on the same partition (hash partitioner, hash(key) % partitions). Three keys may hit only two partitions — partition 2 -> 0 records is normal, since a hash never guarantees an even spread.

Asynchronous produce sends in batches and is an order of magnitude faster. make produce-async sends 200 records; expect batch receipt statistics:

bash
make produce-async

Measured on this machine with small records: about 400 records/s synchronously versus 13000 records/s asynchronously — the gap is entirely "whether each record waits for a network round trip". In async mode both the Successes() and Errors() channels must be drained, otherwise the internal channels block and memory grows:

go
go func() { for msg := range producer.Successes() { _ = msg } }()
go func() { for err := range producer.Errors() { log.Println(err) } }()

Direct partition consumption ​

Reading does not require a consumer group: an offset is just a number inside a partition, so reading can start anywhere, and nothing is committed — repeating the command changes no state, which makes it a safe way to check whether a record is there.

make consume reads 10 records per partition; expect partition / offset / key / headers / value per record:

bash
make consume

The equivalent direct read uses ConsumePartition, with a partition and a start point (oldest / newest or an explicit number):

go
pc, err := consumer.ConsumePartition(topic, partition, sarama.OffsetOldest)
for msg := range pc.Messages() {
    fmt.Println(msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
}

Consumer groups and offset commits ​

Several consumers form a consumer group subscribing to the same topic: partitions are assigned exclusively inside the group — one partition belongs to one member at a time — and the offset is committed to __consumer_offsets after processing, so a crash or restart resumes from the commit point.

make group consumes 10 records as a group; expect a rebalance line in the log and a shrinking make lag afterwards:

bash
make group

The skeleton of the consume loop (full implementation in internal/kafkax/consumer.go):

go
handler := &GroupHandler{OnMessage: func(msg *sarama.ConsumerMessage) { /* handle */ }}
for {
    if err := group.Consume(ctx, []string{topic}, handler); err != nil {
        log.Println(err)
    }
    if ctx.Err() != nil {
        return
    }
}

Three points that commonly go wrong:

  • Consume must sit in a for loop: on rebalance it returns normally (not an error), so a single call leaves the instance "apparently not consuming" after members change.
  • Offset semantics: MarkMessage is only a local mark (it marks offset+1); persistence happens at Commit. Auto-commit plus a processing failure can lose records; manual commit after success gives at-least-once, and duplicates need business-level idempotence.
  • Commit once more before exiting: with --commit-every N, the tail smaller than N is never committed and would be replayed; Cleanup issues one last Commit.

Exact-limit consumption (--limit N) is a real concurrency trap: letting each partition check count < limit on its own overshoots (3 partitions in parallel once delivered 9 records for --limit 6). The fix is to put "check and count" under one lock, and let a partition that gets no slot return without MarkMessage — the offset does not advance, the record can be read again, so "consuming less" never becomes "losing records":

bash
go run . group --limit 20 --manual-commit --commit-every 5

Expect exactly 20 committed records and make lag down by exactly 20.

Topic administration ​

Topic create/list/describe/config/delete go through sarama.ClusterAdmin; the make targets cover daily use:

bash
make topics       # topic list with partitions and replication, expect demo topics listed
make create       # create demo-topic (3 partitions, retention 1h), expect it to appear
make describe     # partitions, leader, ISR and offset range of demo-topic
make config       # effective config values and where each comes from
make delete       # delete demo-topic, expect other topics untouched

Two implementation details:

  • Topic creation is asynchronous: a successful CreateTopic does not mean the metadata is visible yet; poll until describe works (the project's WaitTopicVisible).
  • An empty ISR is a serious signal: the leader has no in-sync replica, so acks=all writes fail — in production this is a failure precursor.

--retention takes a Go duration (24h, 168h default 7 days) and writes retention.ms underneath; --cleanup accepts delete / compact / compact,delete.

Consumer groups and lag ​

Whether consumption keeps up has exactly one reliable signal: lag (records behind = end offset − committed offset). make lag prints per-partition and total lag:

bash
make lag
text
== Consumer lag group=demo-group topic=demo-topic ==
  PARTITION  COMMITTED  END  LAG
  0          3          217  214
  1          2          73   71
  2          1          102  101
  total lag: 386 records

Committed shown as none (value -1) means the group never committed on that partition — the whole range counts as unconsumed. List groups and their states with make groups; expect group names, states and member counts:

bash
make groups

Empty is the normal state — offsets survive process exit (7 days by default, offsets.retention.minutes), so an empty group does not mean its offsets are gone.

End-to-end regression in one shot ​

make e2e chains seven assertions; any failure exits non-zero, so it can run in CI (Continuous Integration):

bash
make e2e                                 # temporary topic, deleted when finished
go run . e2e --messages 500              # a larger data set
go run . e2e --topic my-topic --keep     # reuse your own topic and keep it
StepAssertionWhy it must exist
1 connectbrokers discoverable, controller availablewithout metadata the rest is moot
2 topicmetadata visible after creationcovers the async topic-creation race
3 produceall N records ackedcovers compression, idempotence and acks end to end
4 partitionthe same key maps to the same partitionthe ordering premise holds
5 consumeexactly N records, offsets strictly increasing per partitionnothing lost, duplicated or reordered
6 offsetslag back to the baselineoffsets really committed; a baseline instead of a hardcoded 0 allows non-empty topics
7 cleanupdelete the temporary group and topicrepeatable runs leave the cluster clean

Common issues ​

SymptomLikely causeHow to check
Every command fails to connectcontainer not running / port not publishedmake kafka-status
Connects but always hangsADVERTISED_LISTENERS is a container-internal addresscheck the advertised setting in Running Kafka Locally
create succeeds but describe says notopic creation is asynchronousthe project covers this with WaitTopicVisible; manually run make topics
A group suddenly consumes nothingConsume not called again after rebalanceconfirm the for loop inside ConsumeGroup
Duplicates after manual committhe tail was never committedcheck whether Cleanup issues the final Commit()
e2e fails on a non-empty topicasserting lag=0 while the baseline is not 0assert "back to baseline" instead of lag=0

Appendix: project layout and design ​

The complete project is at docs/public/demos/kafka:

text
docs/public/demos/kafka/
├── main.go                 # entry point
├── cmd/                    # one file per subcommand (cobra)
│   └── topic/              # the topic group lives in its own package
├── internal/
│   ├── cli/                # flags, connection plumbing
│   ├── kafkax/             # all sarama interaction, returns data only
│   └── verify/             # the 7 e2e assertions, one file per step
├── scripts/kafka.sh        # cluster lifecycle (bind-mount storage)
├── Makefile                # shortcuts: kafka-*, health, produce, e2e, ...
└── go.mod
DirectoryOwnsDoes not own
cmd/flag parsing, output format, exit codesno Kafka protocol details, no assertions
internal/cli/global flag binding, connection plumbing, topic name resolutionno business logic, no printing
internal/kafkax/all Kafka interaction: config, produce, consume, topic, lagno printing, no exit codes
internal/verify/the seven assertion steps and the tallynever calls sarama directly

What the layering buys: changing output format touches only cmd; reusing a capability calls kafkax directly; and e2e uses exactly the same wrappers as the subcommands — so a passing e2e means every capability the subcommands rely on works. Code conventions: one subcommand per file; flags live in each command's own struct, never in package-level mutable variables; functions stay under 50 lines; opening and closing connections is centralized in cli.WithClient / cli.WithAdmin.

Command overview:

CommandPurpose
healthconnectivity: broker / controller / topic count
topic create/list/describe/config/deletetopic administration
produceproduce; --async for batches, --keys rotates keys
consumedirect read by --partition / --offset, no group
groupgroup consume; --limit exact limit, --manual-commit manual commits
lag / groupslag and consumer group listing
e2ethe seven end-to-end assertions

References ​

Code and scripts: docs/public/demos/kafka · Related: Kafka Concepts and When to Use It · Running Kafka Locally · Series index

~~~ That is the end ~~~