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
| Item | Requirement |
|---|---|
| Kafka | Started via Running Kafka Locally; make kafka-status shows healthy |
| Go | 1.27.4 (the version declared in the project's go.mod) |
| Dependencies | github.com/IBM/sarama v1.60.2, github.com/spf13/cobra v1.10.2 |
If Go is not installed yet, on macOS use Homebrew:
brew install go
go versionOn Linux download the official binary archive (same version as the table above):
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 versionThe PATH change must go into ~/.bashrc or ~/.zshrc to survive new terminals. Fetch dependencies and compile; no output means success:
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:
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.OffsetOldestThe full template is in internal/kafkax/config.go. What the four values mean:
| Setting | Value | Why |
|---|---|---|
Version | V3_9_0_0 | Matches broker 3.9.1; an older version silently downgrades the protocol |
RequiredAcks | WaitForAll | Returns only after all in-sync replicas persist the record; a single replica crash loses nothing |
Idempotent | true (with MaxOpenRequests=1) | Retries never duplicate records; MaxOpenRequests=1 is a hard requirement of idempotence |
Offsets.Initial | OffsetOldest | A 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:
make health== Cluster health ==
client addresses : localhost:9092
metadata refresh : OK (4ms)
brokers : 1
controller : broker#1 localhost:9092sarama connects lazily:
Broker.Connected()staysfalseuntil 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:
make produceThe core code is only a few lines — the message carries a key and headers (source, seq), and sync mode gets the broker receipt:
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-confirmedIn 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:
make produce-asyncMeasured 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 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:
make consumeThe equivalent direct read uses ConsumePartition, with a partition and a start point (oldest / newest or an explicit number):
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:
make groupThe skeleton of the consume loop (full implementation in internal/kafkax/consumer.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:
Consumemust 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:
MarkMessageis only a local mark (it marks offset+1); persistence happens atCommit. 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;Cleanupissues one lastCommit.
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":
go run . group --limit 20 --manual-commit --commit-every 5Expect 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:
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 untouchedTwo implementation details:
- Topic creation is asynchronous: a successful
CreateTopicdoes not mean the metadata is visible yet; poll until describe works (the project'sWaitTopicVisible). - An empty ISR is a serious signal: the leader has no in-sync replica, so
acks=allwrites 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:
make lag== 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 recordsCommitted 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:
make groupsEmpty 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):
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| Step | Assertion | Why it must exist |
|---|---|---|
| 1 connect | brokers discoverable, controller available | without metadata the rest is moot |
| 2 topic | metadata visible after creation | covers the async topic-creation race |
| 3 produce | all N records acked | covers compression, idempotence and acks end to end |
| 4 partition | the same key maps to the same partition | the ordering premise holds |
| 5 consume | exactly N records, offsets strictly increasing per partition | nothing lost, duplicated or reordered |
| 6 offsets | lag back to the baseline | offsets really committed; a baseline instead of a hardcoded 0 allows non-empty topics |
| 7 cleanup | delete the temporary group and topic | repeatable runs leave the cluster clean |
Common issues
| Symptom | Likely cause | How to check |
|---|---|---|
| Every command fails to connect | container not running / port not published | make kafka-status |
| Connects but always hangs | ADVERTISED_LISTENERS is a container-internal address | check the advertised setting in Running Kafka Locally |
create succeeds but describe says no | topic creation is asynchronous | the project covers this with WaitTopicVisible; manually run make topics |
| A group suddenly consumes nothing | Consume not called again after rebalance | confirm the for loop inside ConsumeGroup |
| Duplicates after manual commit | the tail was never committed | check whether Cleanup issues the final Commit() |
| e2e fails on a non-empty topic | asserting lag=0 while the baseline is not 0 | assert "back to baseline" instead of lag=0 |
Appendix: project layout and design
The complete project is at docs/public/demos/kafka:
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| Directory | Owns | Does not own |
|---|---|---|
cmd/ | flag parsing, output format, exit codes | no Kafka protocol details, no assertions |
internal/cli/ | global flag binding, connection plumbing, topic name resolution | no business logic, no printing |
internal/kafkax/ | all Kafka interaction: config, produce, consume, topic, lag | no printing, no exit codes |
internal/verify/ | the seven assertion steps and the tally | never 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:
| Command | Purpose |
|---|---|
health | connectivity: broker / controller / topic count |
topic create/list/describe/config/delete | topic administration |
produce | produce; --async for batches, --keys rotates keys |
consume | direct read by --partition / --offset, no group |
group | group consume; --limit exact limit, --manual-commit manual commits |
lag / groups | lag and consumer group listing |
e2e | the seven end-to-end assertions |
References
- Apache Kafka documentation
- sarama: the Go client used by the demo project
- franz-go: another popular Go client
- cobra: the command-line framework
Code and scripts: docs/public/demos/kafka · Related: Kafka Concepts and When to Use It · Running Kafka Locally · Series index

