Columns › 4. Reliability › Part 17
Kafka Core Concepts and What to Watch Out For
Kafka 的核心觀念與使用時要注意的事
Kafka looks like a queue but is a partitioned log. This article covers the log model, keys and partitions, replication and acks, idempotent and batched producers, what exactly-once really covers, consumer groups, commit-after-process, offset resets, lag and dead letters, partition sizing, KRaft and when not to use Kafka, with a franz-go producer and consume loop.
In this article
- What this article solves
- Step 1: The log model: topics, partitions, offsets and segments
- Step 2: Keys and partitions: ordering, hot spots and partition count
- Step 3: Replication: leaders, the ISR, acks and min.insync.replicas
- Step 4: Producer settings: idempotence, retries, batching and ordering
- Step 5: What transactions and exactly-once really guarantee
- Step 6: Consumer groups and rebalancing
- Step 7: Commit after processing: a consume loop with franz-go
- Step 8: Offset reset policies and lag monitoring
- Step 9: Poison messages, dead letters and schema evolution
- Step 10: Partition sizing, KRaft and operations
- Step 11: When not to use Kafka
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Message Queues and Event-Driven Design”, compared Kafka, RabbitMQ and NATS, and covered partitions and ordering, consumer groups, delivery semantics, retries and dead letters; those principles hold for every messaging system. This article is only about Kafka: a few parts of its design run against the intuition of a "queue", and most production incidents happen exactly there.
What this article solves
So far example.com/shop has used NATS JetStream for events. As order volume grows, new needs appear: the reporting, search and risk services want to replay order.* events from months back to build their own data, and during promotions the event rate is dozens of times the usual. The team decides to move orders.events to Kafka.
In the first month in production, this happens:
- To scale out consumers, someone grows the topic from 6 to 8 partitions, and the
order.cancelledof an order is processed before itsorder.placed. - A broker fails; the producer had received success responses, yet a few seconds of order events can no longer be found.
- One release of the inventory service processes more slowly, the consumer group rebalances over and over, the same batch is processed several times, and the lag keeps climbing.
- One malformed event stops a single partition dead while the others run normally, and the dashboards only show "total lag is a bit high".
- Someone assumes that with exactly-once enabled the inbox table is no longer needed, and stock is decremented twice.
None of these are defects in Kafka; they come from not using it according to its model. This article covers, in order:
- The log model: topics, partitions, offsets, segments, and the difference between retention and log compaction.
- Keys and partitions: the scope of ordering, hot partitions, and why changing the partition count scrambles the key mapping.
- Replication: leaders, the ISR,
acks,min.insync.replicasand unclean leader election. - Producer settings: the idempotent producer, retries, batching, compression and how in-flight requests affect ordering.
- Transactions and exactly-once: what they really guarantee, and why consumers still need idempotency.
- Consumer groups and rebalancing: cooperative assignment, static membership, and the slow-processing problem.
- Commit after processing: a testable consume loop with franz-go.
- Offset reset policies and lag monitoring.
- Poison messages, dead letters and schema evolution.
- Partition sizing, KRaft and operational pitfalls.
- When not to use Kafka.
| Common misconception | What actually happens |
|---|---|
| A message disappears once it is read | Messages are kept until retention expires; reading only moves the group's own offset |
| The whole topic is ordered | Only a single partition is ordered |
| A success response means it cannot be lost | That depends on acks, min.insync.replicas and the replica count |
| Exactly-once means no duplicates | It only covers read-process-write inside Kafka; external side effects still need idempotency |
| More consumers means faster processing | The partition count caps the parallelism |
| Just add partitions when there are not enough | Partitions can only be added, never removed, and adding them changes where keys land |
Step 1: The log model: topics, partitions, offsets and segments
Kafka's core abstraction is an append-only log. A topic is split into partitions, and each partition is an independent log; producers append messages to the end of some partition, and the broker gives each one an increasing number within the partition, called its offset. Consumers delete nothing when they read; they only remember "the next offset to read".
Figure: The topic orders.events has three partitions; the log of partition 0 is made of several segment files. The two consumers in group inventory share the three partitions, and each partition's log end offset minus its committed offset is the lag.
This model has several important consequences in practice:
- An offset only means something inside a partition. "Offset 8" identifies a message only together with a topic and partition; offsets in different partitions have no order relative to each other.
- Consumption progress belongs to the consumer group. Each group records one committed offset per partition, stored in Kafka's internal
__consumer_offsetstopic. If the reporting service falls three days behind, the inventory service is unaffected, and nothing is "stuck in the queue". - Replay is cheap. As long as the messages are within retention, moving the group's offset back reprocesses them; a new service can read from the beginning under a new group name. This is exactly why
shopwants Kafka. - Kafka does not track the processing state of individual messages. It has no notion of "this one failed, redeliver it later" and no per-message acknowledgement; retries and dead letters are up to the consumer (Step 9).
On disk a partition is not one big file but a series of segment files. Writes only go to the newest one, called the active segment; it is closed and a new one opened when it reaches segment.bytes (1 GiB by default) or has existed longer than segment.ms. The segment is the unit of cleanup, which matters for both cleanup policies below.
Retention and log compaction
Each topic's cleanup.policy decides how old data is cleaned up:
delete(the default): delete by time or size.retention.msdefaults to 7 days, andretention.bytesis a size limit per partition, unlimited by default. Deletion works on whole segments and never touches the active segment, so data actually stays somewhat longer thanretention.ms; a compliance requirement of "definitely gone after 7 days" cannot rely on this setting alone.compact: log compaction. Kafka removes older messages for the same key in the background, keeping at least the latest one for each key. A message with a null value is a tombstone, meaning "delete this key"; it is kept for anotherdelete.retention.msso that lagging consumers get a chance to see that the key was deleted, and only then removed.- Both can be set at once (
compact,delete): data is compacted, and data that is too old is still deleted.
Figure: After compaction each key keeps only its latest record; offsets are not renumbered, they just have gaps. The null for A-2 is a tombstone, removed only after some time.
| Cleanup policy | Fits | Why | Does not fit |
|---|---|---|---|
delete | Event streams: order.placed, payment.completed | Each record is something that happened, and the full order matters | A snapshot of "the latest state of every order" |
compact | State snapshots: the latest state of each order or product | A new service can build the full current state by reading the topic | Consumers that need to see every intermediate change |
compact,delete | Latest state of recent entities only, e.g. carts in 30 days | Snapshot plus a size cap | Long-lived master data |
Two common misuses: making an event stream compact, so that an order's order.placed is overwritten by its later order.paid and a replaying consumer never sees the placement; and treating a compacted topic as a database, expecting only one record right after a write. Compaction is background work and does not touch the active segment, so consumers will certainly read several older values for the same key, and the processing logic must accept that.
Step 2: Keys and partitions: ordering, hot spots and partition count
The producer gives each message a key; the default partitioner hashes the key (murmur2 by default in both the Java client and franz-go) and takes it modulo the partition count to choose a partition. The same key with the same partition count always gives the same result, so messages with the same key are ordered within one partition. Messages without a key are spread across partitions with no order between them.
shop uses the order ID as the key: an order's placed, paid and cancelled are processed in order; different orders have no order between them, and need none. Choosing a key means answering two questions:
- What is the scope that needs ordering? The smaller the better. Use the order ID, not the user ID, because inventory and payment only care about the order of events within one order.
- Will traffic concentrate? With the merchant ID as the key, if one large merchant has half the orders, its partition becomes a hot partition: its consumer cannot keep up while others sit idle, and adding machines does not help, because a partition is given to only one consumer in a group at a time.
Changing the partition count scrambles the key mapping
Partitions can be added but not removed. Adding them looks harmless, but "modulo the partition count" means that when the count changes, most keys move to a different partition. The function below uses franz-go's built-in partitioner, which uses the same algorithm as the Java client, to compute where a key lands:
package kafkax
import "github.com/twmb/franz-go/pkg/kgo"
// PartitionFor returns the partition a key maps to with n partitions, using the Java client's default algorithm (murmur2).
// Use it before adding partitions to estimate how many keys will move.
func PartitionFor(key string, n int) int {
return kgo.StickyKeyPartitioner(nil).ForTopic("").Partition(&kgo.Record{Key: []byte(key)}, n)
}A test with it shows how many keys move when going from 6 to 8 partitions:
package kafkax
import (
"fmt"
"testing"
)
func TestSameKeySamePartition(t *testing.T) {
first := PartitionFor("A-1001", 12)
for i := 0; i < 100; i++ {
if got := PartitionFor("A-1001", 12); got != first {
t.Fatalf("partition changed: %d -> %d", first, got)
}
}
}
func TestAddingPartitionsRemapsKeys(t *testing.T) {
const keys = 10000
moved := 0
for i := 0; i < keys; i++ {
k := fmt.Sprintf("A-%d", i)
if PartitionFor(k, 6) != PartitionFor(k, 8) {
moved++
}
}
t.Logf("6 → 8 partitions: %d of %d keys moved (%.0f%%)", moved, keys, 100*float64(moved)/keys)
if moved == 0 {
t.Fatal("expected some keys to move")
}
}=== RUN TestAddingPartitionsRemapsKeys
partition_test.go:26: 6 → 8 partitions: 7527 of 10000 keys moved (75%)Three quarters of the keys moved. Moving loses no data by itself; the trouble is the transition: order A-1001's order.placed was written to the old partition 3 and not yet consumed; after the partitions are added, order.cancelled is written to the new partition 7 and another consumer processes it first. The first incident at the start of this article happened exactly like this.
Figure: With 6 partitions, A-1001 hashes to partition 3; after growing to 8, the same key lands in partition 7. The placed event still waiting in partition 3 and the cancelled event already handled in partition 7 end up in the wrong order.
Note when reading this figure: Kafka does not move messages that are already written. Old messages stay in their original partition, and only new messages use the new partition count. So the reordering only happens during the transition, but for order state, once is bad enough.
So the partition count should leave room for growth when the topic is created (Step 10). When it really must change, there are two safer approaches:
- Stop writes, then change: pause the producers, wait for consumers to drain the lag to 0, add the partitions, then resume writes. Fits topics that can tolerate a short write pause.
- Migrate to a new topic: create a new topic with more partitions, switch producers to it, and have consumers finish the old topic before reading the new one. More work, but no write pause.
If a topic has no ordering needs (no keys, or consumers that are fully idempotent and order-insensitive), adding partitions directly is fine.
Step 3: Replication: leaders, the ISR, acks and min.insync.replicas
Each partition has replication.factor replicas on different brokers. One of them is the leader, through which all reads and writes go; the others are followers that keep fetching from the leader. The replicas that keep up with the leader form the ISR (in-sync replicas); a follower that falls behind for longer than replica.lag.time.max.ms is removed from the ISR and added back once it catches up.
Figure: The producer writes to the leader with acks=all, and the leader replies only after broker 2 in the ISR has caught up; broker 3 fell too far behind and was removed from the ISR. Consumers only read messages before the high watermark, which every ISR member has.
The producer's acks decides when the leader replies with success:
acks | When the leader replies | How data can be lost | Fits |
|---|---|---|---|
0 | Never; sent counts as success | Any network or broker problem loses data silently | Metrics and logs you can afford to drop |
1 | After the leader writes its own log | The leader fails after replying and before followers copy the record | Throughput first, occasional loss acceptable |
all (-1) | After every replica currently in the ISR has it | Only meaningful with min.insync.replicas (below) | Events that must not be lost: orders, payments |
acks=all has an easily missed hole: "every replica in the ISR has it" is also true when the ISR is just the leader. If two of three replicas fall behind, the ISR shrinks to one and acks=all degrades into acks=1. min.insync.replicas closes the hole: when the ISR is smaller than this number, acks=all writes are rejected (NotEnoughReplicas), and the producer gets an error and retries instead of an unreliable success. Its default is 1, which gives no protection.
A common combination is replication.factor=3, min.insync.replicas=2, acks=all:
- With any one broker down (including during a rolling upgrade), writes continue.
- Every acknowledged message is on at least two brokers, so one failure loses nothing.
- With two brokers down at the same time, writes fail, but never pretend to succeed. This trades availability for consistency, the right trade-off for order events.
If replication.factor is also 2 with min.insync.replicas=2, restarting any one broker makes writes fail, so in practice use at least three replicas.
unclean.leader.election.enable decides what happens when every ISR member fails. The default is false: a new leader may only come from the ISR, and the partition is unavailable until an ISR replica returns. With true, a lagging replica may become leader and the partition is available at once, but the messages it lacks are gone forever, and producers that received success responses never find out. The "it succeeded, yet it is gone" of the second incident is the classic symptom of acks=1 or unclean election. Order and payment topics should keep it false.
Finally, the high watermark: the position every ISR member has written. Consumers only read messages before the high watermark, so offset 6 on the leader in the figure is written but not yet visible; this ensures consumers never read a message that could vanish if the leader changes.
Step 4: Producer settings: idempotence, retries, batching and ordering
When a producer sends a batch and gets no response (a timeout, a dropped connection), it cannot tell whether the broker wrote it, so it can only resend, and a resend can leave two copies in the log. The idempotent producer removes this kind of duplicate: the broker gives each producer a producer ID, the producer numbers each batch per partition with an increasing sequence number, and the broker discards a sequence number it has already seen.
Figure: Batch seq=5 was written, but the response was lost on the network; the producer resends with the same sequence number, the broker recognises that the number was already written, replies with success and does not write it again, so the log holds one copy.
The idempotent producer has a clear scope: it only removes duplicates caused by internal retries of the same producer instance. After a restart the program gets a new producer ID; if the application catches an error and calls send again, that is a new message too. The broker cannot recognise either case, so consumer-side idempotency is still required.
Since Kafka 3.0 the Java client defaults to enable.idempotence=true and acks=all; franz-go also enables idempotent writes and acks=all by default. These are the settings worth understanding (Java client names, with the franz-go equivalents):
| Setting | franz-go | What it does | Watch out for |
|---|---|---|---|
enable.idempotence | On by default; DisableIdempotentWrite turns it off | The broker drops retry duplicates by sequence number | Requires acks=all; does not cover restarts or app-level resends |
acks | RequiredAcks(AllISRAcks()) | Step 3 | Pair with the topic's min.insync.replicas |
retries, delivery.timeout.ms | RecordRetries, RecordDeliveryTimeout | How many retries, and the overall time limit | Prefer limiting total time over the count; delivery.timeout.ms defaults to 2 minutes |
max.in.flight.requests.per.connection | Capped at 5 when idempotent | Requests in flight at once on a connection | Without idempotence, several in-flight requests plus retries reorder messages |
linger.ms, batch.size | ProducerLinger, ProducerBatchMaxBytes | How long to wait and how much to gather per batch | Longer waits mean bigger batches and more throughput, but each message waits that long |
compression.type | ProducerBatchCompression | Compresses per batch (gzip, snappy, lz4, zstd) | Bigger batches compress better; every consumer must decode the codec you choose |
The link between ordering and retries deserves a word. Without idempotence, if two batches for the same partition are in flight and the first fails and is retried while the second succeeds, the order in the log is reversed; the old advice was therefore to set in-flight requests to 1, trading throughput for order. With idempotence the broker rejects out-of-sequence batches, so order within a partition holds with up to 5 requests in flight. That is the most practical reason not to turn idempotence off.
shop's producer:
package kafkax
import (
"context"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
// NewProducer creates the producer for order events.
// franz-go already enables idempotent writes and acks=all by default; we spell them out so readers need not look up defaults.
func NewProducer(brokers []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.DefaultProduceTopic("orders.events"),
kgo.RequiredAcks(kgo.AllISRAcks()), // idempotent writes require acks=all
kgo.ProducerLinger(5*time.Millisecond),
kgo.ProducerBatchCompression(kgo.ZstdCompression(), kgo.SnappyCompression(), kgo.NoCompression()),
// No RecordRetries: with a retry cap, a failed batch also fails every later record buffered for that partition.
// A delivery deadline bounds how long we wait; the caller handles the timeout (e.g. the outbox relay retries next round).
kgo.RecordDeliveryTimeout(30*time.Second),
)
}
// PublishOrderEvent keys by order ID, so all events of one order land in one partition and are consumed in order.
func PublishOrderEvent(ctx context.Context, cl *kgo.Client, orderID, eventID, eventType string, payload []byte) error {
r := &kgo.Record{
Key: []byte(orderID),
Value: payload,
Headers: []kgo.RecordHeader{
{Key: "event-id", Value: []byte(eventID)}, // consumers deduplicate on it
{Key: "event-type", Value: []byte(eventType)},
},
}
return cl.ProduceSync(ctx, r).FirstErr()
}The reasons for a few choices:
ProduceSyncwaits for the result. Order events come from the outbox relay (see “Distributed Transactions: Sagas and the Outbox Pattern”), which must know that the send succeeded before settingpublished_at, so it uses the synchronous version. For high throughput where asynchronous callbacks are fine, useProducewith a callback.- No retry count, a delivery deadline instead. franz-go retries without limit by default; setting
RecordDeliveryTimeoutmeans that when brokers are unavailable for a long time, the error returns to the relay, the outbox keeps the event and the next round resends it, rather than leaving the request hanging. - Compression lists a preference order. franz-go picks the first codec the brokers support; before switching to zstd, make sure every consumer (including ones written in other languages) can decode it.
- The event-id goes in a header. The idempotent producer cannot stop relay resends; consumers deduplicate on this ID.
Step 5: What transactions and exactly-once really guarantee
Kafka's exactly-once semantics (EOS) combine the idempotent producer with transactions. With a transactional.id, a producer can put "messages written to several partitions" and "the consumer group's offset commit" into one transaction that commits or aborts as a whole. A consumer with isolation.level=read_committed only reads messages from committed transactions (the Java client defaults to read_uncommitted, and franz-go also reads uncommitted data by default; change it with FetchIsolationLevel(ReadCommitted())).
This makes one particular kind of flow exactly-once: read from Kafka, process, and write the result back to Kafka. For example, read from orders.events, compute hourly sales, write to sales.hourly: the output messages and the input offsets commit in the same transaction, so after a crash and restart the earlier output is aborted and never appears twice. Kafka Streams' processing.guarantee=exactly_once_v2 is built on this mechanism; franz-go provides GroupTransactSession for this kind of read-write transaction.
But its scope ends there. Once a side effect lands outside Kafka, the transaction cannot reach it.
Figure: The framed part is one Kafka transaction: reading, computing, writing the output topic, and committing the consumed offsets. Writing PostgreSQL and calling the payment gateway on the right sit outside the frame, so they are not undone when the transaction aborts.
Case by case:
| Flow | Can EOS make it exactly-once? | Reason and remedy |
|---|---|---|
Read orders.events → compute → write sales.hourly | Yes | Output and offsets are in the same Kafka transaction |
Read orders.events → decrement stock in PostgreSQL | No | The database write is not in the Kafka transaction; deduplicate with an inbox table in the same database transaction |
Read payment.requested → call the payment gateway | No | An external call cannot be rolled back; use an idempotency key (see “Idempotency and Distributed Locks”) |
Order service writes its database → emits order.placed | No | The dual-write problem; use a transactional outbox |
The fifth incident applied the guarantee of the first row to the second. Decrementing stock is a PostgreSQL write; if the consumer crashes after the database commit and before the offset commit, the same event is processed again after the restart, and a Kafka transaction can do nothing about it. The right approach is still the inbox from “Distributed Transactions: Sagas and the Outbox Pattern”: insert the event ID and decrement stock in the same database transaction.
Transactions also cost something: every commit is a round trip to the transaction coordinator, read_committed consumers only see messages after the transaction ends, and managing transactional.id across rebalances has details to get right. They are only worth it for genuine Kafka-to-Kafka processing; most shop services "read events and write their own database", for which at-least-once plus idempotent consumers is enough, and simpler.
Step 6: Consumer groups and rebalancing
Within a group, a partition is assigned to only one consumer at a time. When membership changes (a new instance starts, one shuts down, one is declared dead, a subscribed topic's partition count changes), the group rebalances and reassigns partitions. Rebalancing is the source of most trouble on the consumer side.
Eager and cooperative
With traditional eager assignment, when a rebalance starts every consumer gives up all its partitions and takes some back once the new assignment is ready. The whole group stops consuming meanwhile; a rolling update of ten instances means ten group-wide pauses.
Figure: When consumer C3 joins, eager assignment (top) makes C1 and C2 give up all their partitions and the whole group pauses; cooperative assignment (bottom) hands only partitions 2 and 5 to C3, and the other partitions held by C1 and C2 keep being consumed. The final assignment is the same; the difference is how much stops along the way.
Cooperative (incremental) assignment (the CooperativeStickyAssignor added in Kafka 2.4) moves only the partitions that need to move, and the rest keep being consumed during the rebalance. franz-go's current default is cooperative-sticky. Note that eager and cooperative members are incompatible in one group; switching from eager to cooperative follows the official rolling-upgrade procedure in two deployments, not a plain config change and restart.
Since Kafka 4.0 there is also a next-generation consumer group protocol (KIP-848) in which the broker computes the assignment, further reducing the impact of rebalances; it needs support in both broker and client, so check your version combination before adopting it.
Static membership
On Kubernetes, every Pod restart makes the consumer join as a new member and triggers a rebalance, and leaving triggers another. Static membership lets a consumer join with a fixed group.instance.id (InstanceID in franz-go): if it returns before the session times out, the broker gives its partitions back without a rebalance.
It fits deployments with stable names such as a StatefulSet: use the Pod name as the instance ID and make the session timeout long enough to cover a restart. The cost: when an instance really dies, its partitions are only handed over after the session timeout, and nobody consumes them meanwhile. Two instances mistakenly sharing an instance ID keep fencing each other out.
Processing too slowly
The Java client has two liveness checks: a background thread sends heartbeats, and no heartbeat within session.timeout.ms (45 seconds by default since 3.0) means the member is dead; separately, more than max.poll.interval.ms (5 minutes by default) between two poll() calls also gets it kicked out of the group. The latter is the classic slow-processing incident: one poll() returns max.poll.records (500 by default) records, one second each exceeds 5 minutes; once kicked out, the partitions go to someone else, who reads from the last committed offset and processes the same batch again, while the original consumer finishes and tries to commit partitions it no longer owns. This was the third incident: rising lag, duplicate processing, endless rebalances, and the slower it gets the worse it gets.
franz-go separates heartbeating from fetching and has no max.poll.interval.ms limit by default, but the problem takes another shape: a rebalance can happen while you are halfway through a batch, and the offsets you commit afterwards may belong to partitions already given to someone else. BlockRebalanceOnPoll prevents rebalances between receiving a batch and calling AllowRebalance, guaranteeing that you commit partitions you own; the cost is that if this takes longer than the rebalance timeout (RebalanceTimeout, 60 seconds by default), the member is kicked out of the group.
Whatever the client, the remedies are the same:
- Bound the batch size: lower
max.poll.recordsin Java; pass a limit toPollRecordsin franz-go. - Bound the time per message: wrap each message in
context.WithTimeoutso a stuck downstream does not cause an endless wait. - Estimate the worst case: batch size × attempts × per-message timeout, plus backoff, must stay below
max.poll.interval.msorRebalanceTimeout. - Move slow work out of the consume loop: for something like generating a PDF, have the consumer only write a job row to the database and let a background worker process it. Do not stretch timeouts to accommodate slow work; that makes genuinely dead consumers take far longer to detect.
Step 7: Commit after processing: a consume loop with franz-go
“Message Queues and Event-Driven Design” explained that the commit timing decides the delivery semantics. The Kafka-specific trap is auto-commit: the Java client defaults to enable.auto.commit=true and every auto.commit.interval.ms (5 seconds by default) commits "the position polled so far", not "the position processed so far". If processing happens synchronously on the thread that calls poll(), the result is roughly at-least-once; but as soon as messages are handed to other goroutines or threads, auto-commit can commit before processing finishes, and a crash loses those messages: at-most-once.
Figure: At the top, committing before processing: a crash mid-processing restarts from 8 and message 7 is lost. At the bottom, committing after processing: a crash before the commit restarts from 7 and message 7 is processed again.
shop's inventory service disables auto-commit and commits after processing. To test it without a broker, the consume loop depends only on a three-method interface, which *kgo.Client satisfies directly:
package kafkax
import (
"context"
"errors"
"fmt"
"log/slog"
"strconv"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
// Source is the three methods the consume loop needs; *kgo.Client satisfies it, tests use a fake.
type Source interface {
PollRecords(ctx context.Context, maxPollRecords int) kgo.Fetches
CommitRecords(ctx context.Context, rs ...*kgo.Record) error
AllowRebalance()
}
// ErrPoison marks a message that will never succeed however often it is retried (e.g. malformed); it goes straight to the dead-letter topic.
var ErrPoison = errors.New("poison message")
type Consumer struct {
Src Source
Handle func(context.Context, *kgo.Record) error // must be idempotent: at-least-once delivery
DeadLetter func(context.Context, *kgo.Record, error) error // writes to the dead-letter topic
MaxAttempts int // max tries for transient errors
Backoff time.Duration // wait before each retry (0 in tests)
Timeout time.Duration // processing limit per message
BatchSize int // max records per poll
}
// Run polls a batch -> processes it in order -> commits what was processed -> allows a rebalance.
// Committing after processing gives at-least-once: crash before the commit and the batch is processed again.
func (c *Consumer) Run(ctx context.Context) error {
for {
fs := c.Src.PollRecords(ctx, c.BatchSize)
if fs.IsClientClosed() {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
fs.EachError(func(topic string, p int32, err error) {
slog.Warn("fetch error", "topic", topic, "partition", p, "err", err)
})
var done []*kgo.Record
var stopErr error
fs.EachPartition(func(p kgo.FetchTopicPartition) {
for _, r := range p.Records {
if stopErr != nil {
return
}
if err := c.process(ctx, r); err != nil {
stopErr = err // later messages in this partition must not be skipped; leave them for next time (or the next consumer)
return
}
done = append(done, r)
}
})
// Commit only what was really processed; CommitRecords takes the highest offset + 1 per partition.
// On shutdown ctx is already cancelled but the commit must finish, so use an uncancellable context with a deadline.
if len(done) > 0 {
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
err := c.Src.CommitRecords(cctx, done...)
cancel()
if err != nil {
c.Src.AllowRebalance()
return fmt.Errorf("commit: %w", err)
}
}
c.Src.AllowRebalance() // with kgo.BlockRebalanceOnPoll: partitions move only after the commit
if stopErr != nil {
return stopErr
}
}
}
// process handles one message: transient errors are retried with backoff; poison messages or exhausted retries go to the dead letter.
// It returns an error only when even the dead letter cannot be written, so the consumer stops without committing.
func (c *Consumer) process(ctx context.Context, r *kgo.Record) error {
var err error
for attempt := 1; attempt <= c.MaxAttempts; attempt++ {
hctx, cancel := context.WithTimeout(ctx, c.Timeout)
err = c.Handle(hctx, r)
cancel()
if err == nil || errors.Is(err, ErrPoison) {
break
}
if ctx.Err() != nil {
return ctx.Err() // shutting down: do not dead-letter the message as failed
}
if attempt < c.MaxAttempts {
time.Sleep(c.Backoff * time.Duration(attempt))
}
}
if err == nil {
return nil
}
if dlqErr := c.DeadLetter(ctx, r, err); dlqErr != nil {
return fmt.Errorf("dead letter %s/%d@%d: %w", r.Topic, r.Partition, r.Offset, dlqErr)
}
return nil
}
// ToDeadLetter writes the failed message unchanged to the dead-letter topic, adding its source position and the error as headers.
func ToDeadLetter(cl *kgo.Client, topic string) func(context.Context, *kgo.Record, error) error {
return func(ctx context.Context, r *kgo.Record, cause error) error {
dl := &kgo.Record{
Topic: topic,
Key: r.Key,
Value: r.Value,
Headers: append(r.Headers[:len(r.Headers):len(r.Headers)],
kgo.RecordHeader{Key: "dlq-source", Value: []byte(r.Topic + "/" + strconv.Itoa(int(r.Partition)) + "@" + strconv.FormatInt(r.Offset, 10))},
kgo.RecordHeader{Key: "dlq-error", Value: []byte(cause.Error())},
),
}
return cl.ProduceSync(ctx, dl).FirstErr()
}
}
// NewConsumerClient creates the consumer-group client for the inventory service.
// A non-empty instanceID enables static membership (e.g. the StatefulSet Pod name).
func NewConsumerClient(brokers []string, instanceID string) (*kgo.Client, error) {
opts := []kgo.Opt{
kgo.SeedBrokers(brokers...),
kgo.ConsumerGroup("inventory"),
kgo.ConsumeTopics("orders.events"),
kgo.DisableAutoCommit(), // commit manually, after processing
kgo.BlockRebalanceOnPoll(), // no partition is taken away between a poll and AllowRebalance
kgo.Balancers(kgo.CooperativeStickyBalancer()),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), // same as auto.offset.reset=earliest
}
if instanceID != "" {
opts = append(opts,
kgo.InstanceID(instanceID),
kgo.SessionTimeout(60*time.Second), // leave time for a restart without triggering a rebalance
)
}
return kgo.NewClient(opts...)
}The decisions in this code:
DisableAutoCommit+CommitRecordsafter processing.CommitRecordscommits the highest offset plus one per partition, so you only pass the records that were processed.- In order within a partition, stop on what cannot be handled. If a message cannot even be written to the dead letter, the loop commits only what came before it and returns an error so the service restarts; it must never skip it and commit later offsets, or it is gone for good.
- The commit uses a different context. On shutdown
ctxis already cancelled, but what was processed should still be committed, otherwise every deployment reprocesses a batch.context.WithoutCancelkeeps the context's values, drops the cancellation, and a deadline is added on top. BlockRebalanceOnPoll+AllowRebalance. Rebalances are allowed only after the commit, so we never commit to partitions we no longer own.Handlemust be idempotent. Even with all of the above, rebalances, crashes and failed commits still cause duplicates; the inventory service's handler deduplicates on theevent-idheader in its inbox table.
The tests use a fake Source: the first PollRecords returns a prepared batch, later calls return "client closed", and it records how far each partition was committed. The second test checks that when the dead letter cannot be written, the loop commits only the offsets before the failure:
// fragment: the full file is consume_test.go; fakeSource and batch are omitted
func TestDLQDownStopsWithoutSkipping(t *testing.T) {
src := &fakeSource{batch: batch(3, 0), committed: map[int32]int64{}}
handle := func(_ context.Context, r *kgo.Record) error {
if r.Offset == 1 {
return ErrPoison
}
return nil
}
dlq := func(context.Context, *kgo.Record, error) error { return errors.New("broker unavailable") }
err := newConsumer(src, handle, dlq).Run(context.Background())
if err == nil {
t.Fatal("want error when dead letter fails")
}
// only offset 0 is committed; offsets 1 and 2 are processed again after a restart, never skipped
if src.committed[0] != 1 {
t.Fatalf("committed p0 = %d, want 1", src.committed[0])
}
}The other test confirms that transient errors are retried until they succeed, a poison message is tried once and goes to the dead letter, and both partitions are committed up to their last record. Separating the client behind an interface matches “Testing in Go: Table-Driven Tests, httptest and Integration Tests”: the loop logic is tested with a fake, and the part that talks to a real broker is left to a few integration tests.
Wiring it into cmd/inventory/main.go:
// fragment: cmd/inventory/main.go
cl, err := kafkax.NewConsumerClient(cfg.KafkaBrokers, os.Getenv("POD_NAME"))
if err != nil {
return err
}
defer cl.Close() // a non-static member leaves the group here, so its partitions move at once
dlqProducer, err := kafkax.NewProducer(cfg.KafkaBrokers)
if err != nil {
return err
}
defer dlqProducer.Close()
c := &kafkax.Consumer{
Src: cl,
Handle: h.HandleOrderEvent, // decode, check version, inbox dedup, decrement stock
DeadLetter: kafkax.ToDeadLetter(dlqProducer, "orders.events.dlq"),
MaxAttempts: 3,
Backoff: 100 * time.Millisecond,
Timeout: time.Second,
BatchSize: 10, // worst case about 10 × (3 × 1s + 0.3s) = 33s, below the default RebalanceTimeout of 60s
}
if err := c.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
return err
}ctx comes from the signal handling in “Configuration and Graceful Shutdown in Go”: it is cancelled on SIGTERM, Run finishes the message in hand, commits and returns, and Close then leaves the group.
Step 8: Offset reset policies and lag monitoring
Where to start without an offset
When a group reads a partition for the first time, or its committed offset is no longer in the log (deleted by retention), the consumer must decide where to start; that is auto.offset.reset:
| Value | Behaviour | Fits | Risk |
|---|---|---|---|
earliest | Start from the oldest message | Business consumers that must not miss anything: inventory, payment, reporting | A new group must work through all history, which can take long |
latest | Read only messages arriving from now on | Consumers that only care about live data: live dashboards, cache invalidation | When a group's offsets expire, everything in between is silently skipped |
none | Fail if no offset is found | Consumers that would rather stop than guess | Needs manual intervention |
The Java client defaults to latest, a common source of missed messages: when a new service goes live, events written before its deployment are never processed. franz-go starts at the beginning of the partition by default, but shop's code still writes ConsumeResetOffset(kgo.NewOffset().AtStart()) explicitly rather than relying on the default.
Another trap is that group offsets expire. When a group has no live members, its committed offsets are kept only for offsets.retention.minutes (7 days by default since Kafka 2.0). If the reporting service is down for more than a week and then starts, its offsets are gone and auto.offset.reset decides: latest skips the week, earliest starts again from the topic's oldest data. Check this before restarting a consumer that has been off for a long time.
Resetting offsets by hand
To reprocess a period of events after fixing a bug, or to skip a known stretch of bad data, use the tools that ship with Kafka. A group can only be reset when it has no live members, so scale the consumers to 0 first:
# show progress and lag per partition
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --describe --group reporting
# preview first: move the reporting group back to a point in time
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group reporting \
--topic orders.events --reset-offsets --to-datetime 2026-11-19T00:00:00.000 --dry-run
# execute once it looks right
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group reporting \
--topic orders.events --reset-offsets --to-datetime 2026-11-19T00:00:00.000 --executeMoving back means reprocessing, so consumers must be idempotent. This is another benefit of the "at-least-once plus idempotency" design: replay becomes a safe routine operation rather than a gamble.
Lag monitoring
The LAG column from --describe is each partition's log end offset minus its committed offset. A few points when monitoring it:
- Look per partition, not just the total. In the fourth incident one partition was stuck on a poison message and its lag kept rising, but the total was diluted by the healthy partitions and only looked "a bit high". Alert on the lag of a single partition rising steadily, or on a single partition's committed offset not moving for a long time.
- Look at the trend, not just the number. Lag rising during a promotion and then falling is normal; only a steady, monotonic rise means consumption cannot keep up.
- Convert lag into time. A lag of 10,000 is one second on a topic with ten thousand messages per second, and sixteen hours on one with ten per minute. "The age of the oldest unprocessed message" makes a good metric.
- Raise a special alert when lag approaches the retention period. Once lag exceeds retention, unprocessed messages are deleted, and that is genuine data loss.
The metrics can come from an exporter of group state, or be computed inside the consumer from each partition's HighWatermark in franz-go's Fetches and the offset it has processed, feeding the metrics system from “Observability in Go: Logs, Metrics and Tracing”.
Step 9: Poison messages, dead letters and schema evolution
Kafka has no built-in dead-letter queue and no "redeliver this later" mechanism; the consumer can only decide how far to commit. So a message that can never be processed (malformed, or referring to a product that does not exist) can be handled in three ways:
- Retry forever: the partition stops and everything behind it waits. Only reasonable when "order matters more than availability, and the problem will certainly be fixed".
- Skip and record: write it to a dead-letter topic (
orders.events.dlq) with its source position and the error, then continue. The consume loop above does this. - Retry topics: failed messages first go to
orders.events.retry, where another consumer processes them after a delay, and only repeated failures go to the dead letter. Fits situations where temporary downstream failures are common, but it breaks per-key ordering.
Dead letters have an ordering catch: if A-1001's order.placed goes to the dead letter, the later order.cancelled is still processed, and the inventory service may "release a reservation that was never made". The handler must recognise this, for example by giving each order's events a sequence number and, on a gap, marking that key as pending instead of carrying on as usual. A dead-letter topic needs monitoring and a replay procedure; a dead letter nobody looks at is no different from throwing the message away.
Error classification follows “Timeouts, Retries and Circuit Breakers”: transient errors (a database timeout) are retried with backoff inside the consumer; permanent errors (decoding or validation failures) are wrapped as ErrPoison and go straight to the dead letter without wasting retries.
Schema evolution
“Message Queues and Event-Driven Design” already covered compatibility rules and envelope design. On Kafka, two points deserve emphasis:
- Retention is the compatibility window. On a topic kept for 30 days, consumers must understand every event version from those 30 days; on a compacted topic, a key that has not been updated for a long time may still be in a format several versions old. New fields need defaults, and a field can only be removed once all old data has expired or been overwritten.
- A schema registry guards the contract. At larger scale, use a schema registry with Avro or Protocol Buffers, which checks compatibility when a producer registers a new schema version and stops contract-breaking changes before deployment, rather than letting consumers fail to decode in the middle of the night.
Step 10: Partition sizing, KRaft and operations
Partition count
The partition count caps consumer parallelism, cannot be reduced, and scrambles key mapping when increased, so it needs thought when the topic is created. One way to estimate:
- Measure the throughput of one consumer handling one partition (including the database writes), say 300 messages per second.
- Estimate the peak write rate and two or three years of growth, say 3,000 messages per second at a promotion peak.
- The partition count is at least the ratio (10), multiplied by growth and headroom, rounded to a number with many divisors such as 24 or 30, so that 2, 3, 4 or 6 consumer instances all divide it evenly.
More partitions is not always better either: each partition has its own files and memory on every replica, a broker failure requires electing a new leader for every partition it led, so more partitions mean slower recovery; and producer batches are per partition, so too many partitions make batches smaller, compression worse and latency higher. Topics without ordering needs need not over-provision, since partitions can simply be added later; only keyed topics need enough from the start.
When creating a topic, set every key setting explicitly rather than relying on auto-creation:
kafka-topics.sh --bootstrap-server kafka:9092 --create --topic orders.events \
--partitions 24 --replication-factor 3 \
--config min.insync.replicas=2 \
--config retention.ms=2592000000retention.ms=2592000000 is 30 days. The broker setting auto.create.topics.enable defaults to true: when code misspells a topic name, the broker creates a new topic with the default settings (often a single replica and few partitions), and messages quietly go somewhere nobody reads. Turn it off in production, and create every topic through reviewed scripts or IaC.
KRaft and ZooKeeper
Kafka used to keep cluster metadata (the broker list, topic configuration, partition leaders) in ZooKeeper. KRaft mode has Kafka's own controller nodes manage the metadata with the Raft consensus protocol, so no separate ZooKeeper ensemble needs to be run:
- Since Kafka 3.3, KRaft can be used in production for new clusters.
- Kafka 4.0 removed ZooKeeper mode; 4.x runs only in KRaft mode.
- An existing ZooKeeper-based cluster must complete its migration to KRaft on a 3.x release before upgrading to 4.x; it cannot jump directly.
Build new clusters with KRaft; plan the migration of an old cluster as a project of its own and rehearse it in a test environment first.
Operational pitfalls
- Message size limits: the broker's
message.max.bytes, the topic'smax.message.bytesand the producer'smax.request.sizeall default to around 1 MB and must be changed together. Better than raising them is keeping large files out of events and putting only an object-storage location in the event. - Disk: with time-based retention, usage follows traffic; promotion traffic times 30 days of retention may exceed capacity. Monitor disk and set
retention.bytesas a ceiling. - Under-replicated partitions:
kafka-topics.sh --describe --under-replicated-partitionslists partitions whose ISR is smaller than their replica count. When it is not empty, some broker is behind or down, and restarting another broker now may drop the ISR belowmin.insync.replicasand make writes fail. In a rolling restart, touch one broker at a time and wait for this list to empty before the next. - Client and broker versions: new features (cooperative assignment, the next-generation group protocol, transaction improvements) need support on both sides; check compatibility before upgrading.
- More consumer instances than partitions: the extras just sit idle, which happens easily when an HPA scales consumers on CPU; cap the scaling at the partition count.
Step 11: When not to use Kafka
Kafka fits high-throughput event streams that need retention and replay and have several independent downstream consumers. Its price is operating a distributed cluster and having the whole team understand everything in this article. Many needs are well served by simpler tools:
| Need | Suggestion | Why |
|---|---|---|
| Several downstreams replay months of events; events are the data backbone | Kafka | Retention and replay are its core model, and consumer groups are independent |
| Events between services, modest volume, small team | NATS JetStream (shop's current choice) | Simple to deploy and run, with persistence, acknowledgements and replay |
| Work queues: per-task retries, delayed execution, priorities | RabbitMQ or JetStream | Per-message acks and redelivery; Kafka's offset model lets one slow task block a partition |
| Complex routing rules (by header, by type) | RabbitMQ | Exchange routing; Kafka only has topics and consumer-side filtering |
| The caller needs the result immediately | gRPC or HTTP | Request-response over a messaging system only adds complexity |
| Background jobs at tens per second, data already in PostgreSQL | A job table plus FOR UPDATE SKIP LOCKED | No new component, and jobs sit in the same transaction as the business data |
Two more criteria:
- Is a managed service available? A cloud provider's managed Kafka removes most broker operations, but partition planning, consumer design and lag monitoring are still yours.
- Do you only need an outbox to send events to one or two services? Then the existing messaging system is enough; consider Kafka when "several teams want to build their own data from the same event stream". “From Monolith to Microservices: Evolving the Architecture at 100K, 1M and 10M Scale” discusses that turning point.
Common pitfalls
- Making an event stream
compact: an order's older events are overwritten by newer ones, and a replay never seesorder.placed. - Assuming data is certainly gone when retention expires: deletion works per segment and never touches the active segment; compliance needs separate handling.
- Adding partitions to a keyed topic directly: most keys move, and during the transition one order's events run out of order.
- Keying by a field where traffic concentrates: a hot partition overloads one consumer, and adding machines does not help.
acks=allwithoutmin.insync.replicas: once the ISR shrinks to one, it isacks=1.- Two replicas with
min.insync.replicas=2: restarting any broker makes writes fail. - Enabling unclean leader election: the partition recovers quickly, but acknowledged messages may vanish forever.
- Turning idempotence off while allowing several in-flight requests: retries reorder messages within a partition.
- Believing exactly-once covers databases and external calls: it only covers Kafka to Kafka; database writes still need an inbox, external calls an idempotency key.
- Auto-commit with asynchronous processing: it commits the polled position, so a crash mid-processing loses messages.
- Batches that take too long: exceeding
max.poll.interval.msor the rebalance timeout gets the member kicked out, with duplicate processing and endless rebalances. - Skipping a failed message and committing later offsets: that message is gone for good; if the dead letter cannot be written, stop.
- Relying on the default
auto.offset.reset: Java's defaultlatestmakes a new service miss events from before its deployment, and the same happens after group offsets expire. - Monitoring only total lag: a stuck partition is diluted by the others until its lag exceeds retention and the data is deleted.
- Dead letters nobody reads: a dead letter equals a discarded message, and later events for the same key must account for the missing one.
- Leaving
auto.create.topics.enableon: a misspelled topic name creates a single-replica topic nobody reads. - More consumer instances than partitions: the extras sit idle; cap autoscaling at the partition count.
Key takeaways
- Kafka is a partitioned append-only log: messages are kept until retention expires and reading only moves the group's own offset, so replay is cheap, but retries and dead letters are the consumer's job.
- Choose the cleanup policy by the nature of the data:
deletefor event streams,compactfor state snapshots; both work per segment and leave the active segment alone. - The key determines the partition and the scope of ordering; choose the narrowest key with spread-out traffic. Partitions can only be added, and adding them moves most keys, so keyed topics need enough partitions from the start.
- For topics that must not lose data, use
replication.factor=3,min.insync.replicas=2,acks=all, and keep unclean leader election off. - Keep the idempotent producer: it removes internal-retry duplicates and keeps per-partition order with several requests in flight; it does not cover restarts or app-level resends.
- Exactly-once only covers read-process-write from Kafka to Kafka; writing a database or calling an external service still needs an inbox or an idempotency key.
- Use cooperative assignment and static membership to soften rebalances; bound batch size and per-message time so the worst case stays below the liveness limits.
- Disable auto-commit, commit after processing, and move past a failed message only once it is in the dead letter; if the dead letter cannot be written, stop rather than skip.
- Set the offset reset policy explicitly and watch for group offset expiry; monitor lag per partition and convert it into time.
- Size partitions from measured per-partition throughput and the peak; build new clusters on KRaft; create topics with scripts and turn auto-creation off.
- When volume is small, when you need per-message acks or complex routing, or when the team cannot run a cluster, choose a simpler tool.
References
- Design (Apache Kafka documentation): the log, replication and the ISR, idempotent producers and transactions, static membership and log compaction, used in steps 1 and 3 to 6.
- Topic Configs (Apache Kafka documentation): the defaults of
cleanup.policy,retention.ms,segment.bytes,min.insync.replicasandunclean.leader.election.enable, used in steps 1 and 3. - Producer Configs (Apache Kafka documentation):
acks,enable.idempotence,delivery.timeout.msandmax.in.flight.requests.per.connection, used in step 4. - Consumer and Share Consumer Configs (Apache Kafka documentation):
session.timeout.ms,max.poll.interval.ms,max.poll.records,enable.auto.commit,auto.offset.resetandisolation.level, used in steps 5 to 8. - Broker Configs (Apache Kafka documentation):
offsets.retention.minutes,auto.create.topics.enableandmessage.max.bytes, used in steps 8 and 10. - kgo (franz-go package documentation): the default cooperative-sticky balancer, unlimited retries,
RebalanceTimeout,BlockRebalanceOnPolland the start offset, used in steps 4 and 6 to 8. - KIP-429: Kafka Consumer Incremental Rebalance Protocol (Kafka Improvement Proposal): incremental cooperative rebalancing, used in step 6.
- KIP-500: Replace ZooKeeper with a Self-Managed Metadata Quorum (Kafka Improvement Proposal): replacing ZooKeeper with KRaft for cluster metadata, used in step 10.
Next
This article dealt with reliability inside Kafka: nothing lost, nothing reordered, duplicates absorbed. But order, inventory and payment data live in three databases, and even with events delivered reliably, consistency across services still has to be designed; the narrow scope of exactly-once transactions also shows how hard "one transaction around everything" is in a distributed system. The next article, “Choosing a Distributed Transaction: 2PC, 3PC, TCC and Saga”, compares these approaches side by side, with the guarantees, costs and fitting scenarios of each.