Covers Kafka's partitioned log model, consumer groups and partition assignment, offset commit strategies in Confluent.Kafka (auto commit, StoreOffset, manual Commit), rebalancing (eager versus cooperative-sticky, max.poll.interval.ms), consumer lag and its causes, and the resulting at-least-once guarantee with idempotent processing.
A Kafka topic is a set of partitions, each an append-only log ordered by offset. Many producers write and many consumer groups read at once. Records are retained by time or size, or by compaction, which keeps only the latest record per key. In a consumer group, each partition goes to one member, so partitions cap parallelism.
The consumer commits offsets, meaning "everything before this is done". Confluent.Kafka's defaults store offsets on consume and auto-commit, which can skip records on a crash. The safe pattern is EnableAutoOffsetStore = false with StoreOffset after processing. That gives at-least-once: a crash or rebalance replays uncommitted records, so handlers must be idempotent.
Lag comes from slow handlers, too few partitions, hot keys or rebalance storms. There is no built-in DLQ. The trade-off: high throughput and replay, but the consumer owns retries, dead-lettering and offset discipline.
"Kafka is a distributed log, not a queue. A topic is split into partitions; a producer's key is hashed to a partition, and each partition is an ordered, immutable sequence of records with increasing offsets. Records aren't deleted when read; they stay for the retention period, or forever per key with compaction. A consumer group is how you scale reading: the group coordinator assigns each partition to exactly one member, so twelve partitions means at most twelve useful consumers. Each group tracks its own committed offset per partition in the
__consumer_offsetstopic, which is why a new group can replay from the start without affecting anyone else.The commit is the delivery guarantee. Confluent.Kafka's defaults auto-commit every five seconds whatever offsets have been stored, and by default it stores an offset as soon as
Consumereturns, so a crash can commit records you never finished: at-most-once by accident. I setEnableAutoOffsetStore = falseand callStoreOffsetonly after the record is fully processed; auto-commit then flushes those offsets in the background. That is at-least-once. On a crash or a rebalance, the new owner starts at the last committed offset and replays a few records, so my handler is idempotent, typically an upsert or an inbox row keyed on topic, partition and offset or a business id.For example, at [company] our [order-projection consumer] had [lag growing to millions during peak]. The cause was [a handler doing a synchronous HTTP call per record, which pushed poll intervals past
max.poll.interval.ms, so the broker kicked consumers out and the group rebalanced every few minutes]. We [batched the lookups, switched to the cooperative-sticky assignor and added partitions to a new topic], and [lag stayed under a few thousand]. The mistake I see is treating Kafka like Service Bus: expecting a DLQ, per-message retry or delay, which Kafka simply doesn't have."
| Term | Meaning |
|---|---|
| Partition | Ordered log; unit of parallelism and ordering |
| Offset | Position of a record in a partition |
| Consumer group | Set of consumers sharing a subscription; each partition to one member |
| Committed offset | Where the group resumes after restart or rebalance |
| Lag | Log end offset minus committed offset, per partition |
| Rebalance | Reassignment of partitions when membership changes |
| Compaction | Keeps latest record per key; tombstones (null value) delete |
| Strategy | Settings | Guarantee | Notes |
|---|---|---|---|
| Defaults | EnableAutoCommit = true, EnableAutoOffsetStore = true |
At-most-once-ish (can skip) | Offsets stored on consume, committed every 5 s |
| Store after processing | EnableAutoOffsetStore = false, StoreOffset(result) |
At-least-once | Recommended default; cheap background commits |
| Manual sync commit | EnableAutoCommit = false, Commit(result) |
At-least-once | Simple, but a broker round trip per commit; commit per batch |
| Transactions (EOS) | Transactional producer + SendOffsetsToTransaction |
Exactly-once within Kafka | Only when output goes to Kafka |
| Cause | Signal | Fix |
|---|---|---|
| Slow handler | Steady lag growth on all partitions | Batch I/O, parallelise within a partition by key, scale DB |
| Too few partitions | Members idle or maxed at partition count | New topic with more partitions (keys remap) |
| Hot partition | Lag on one partition only | Better key, or split a hot key |
| Rebalance storms | Frequent Revoked/Assigned logs |
Faster poll loop, max.poll.interval.ms, cooperative-sticky, static membership |
| Poison record | One partition stuck at one offset | Dead-letter topic after N attempts |
A projection consumer on 12 partitions processed 3,000 records per second normally, but a slow geocoding call (800 ms p95) made polls exceed the 300-second max.poll.interval.ms during a burst, triggering a rebalance every few minutes and lag of 4 million. Caching geocodes and processing per-key in parallel inside each partition brought throughput to 9,000 per second and rebalances to zero.
Checks the candidate understands Kafka's log model and can run a consumer that neither loses records nor drowns in rebalances.
Green flags
Red flags
topic: orders (3 partitions)
p0: [0][1][2][3][4][5] <- log end offset 6
p1: [0][1][2][3]
p2: [0][1][2][3][4][5][6][7]
group "projection": committed p0=4, p1=4, p2=5 -> lag = 2 + 0 + 3 = 5
group "audit": committed p0=0, p1=0, p2=0 -> replaying from the start
The broker doesn't track per-record state. That is why Kafka is fast and cheap per record, and why per-record features (delay, DLQ, individual ack) don't exist.
The group coordinator (a broker) tracks members via heartbeats (session.timeout.ms, default 45 s in recent clients) and the poll loop (max.poll.interval.ms, default 300 s). If a member stops heartbeating or doesn't call Consume within the poll interval, it is removed and partitions are reassigned.
PartitionAssignmentStrategy.CooperativeSticky) only moves the partitions that need to move, in incremental rounds.GroupInstanceId) lets a restarting pod rejoin without a rebalance within the session timeout; useful for rolling deploys.Handle SetPartitionsRevokedHandler to commit stored offsets for partitions you're about to lose.
Consume returns a ConsumeResult with TopicPartitionOffset. Committing offset N+1 means "I've done everything up to N". Commits are per partition, so you can't commit record 7 while 5 is still running in the same partition without skipping 5 on restart. If you process records concurrently within a partition, track the lowest contiguous completed offset and only store that.
consume r5 -> process (DB commit) -> StoreOffset(r5) -> [auto-commit flushes 6]
^ crash here: r5 replayed after restart (duplicate)
consume r5 -> StoreOffset(r5) -> process
^ crash after commit, before process: r5 skipped (loss)
So: store after processing for at-least-once. Make processing idempotent by business key, or by storing (topic, partition, offset) in the same DB transaction as the change; you can even keep offsets in your database and seek to them on assignment (exactly-once-ish into one DB).
There is no DeliveryCount. Patterns: retry in-process a few times with backoff; then produce the record to a dead-letter topic with error headers, and store the offset to move on. For delayed retries, use retry topics with increasing delays (consumer pauses until the record's due time). Respect ordering: if the key's order matters, sending one record to a DLT breaks it; you may need to park the key.
Acks = All with min.insync.replicas = 2 and replication factor 3 is the durable baseline. EnableIdempotence = true prevents duplicates and reordering from producer retries. LingerMs and BatchSize trade latency for throughput. Use Produce with a delivery handler for throughput and ProduceAsync when you need to await each result.
Azure Event Hubs exposes a Kafka endpoint (Standard tier and above), so Confluent.Kafka works with SASL/OAUTHBEARER or a connection string; but it isn't a full Kafka (for example, compaction and transactions support differ by tier, and you can't tune broker configs). Confluent Cloud on Azure in Australia East is the managed full-Kafka option.
kafka-consumer-groups --describe to watch lag per partition while a consumer sleeps 50 ms per record.max.poll.interval.ms; observe the rebalance and duplicate processing; switch to cooperative-sticky and compare.An at-least-once Kafka consumer: offsets are stored only after processing, revoked partitions are committed, and poison records go to a dead-letter topic.
// OrdersConsumer.cs
using System.Text;
using Confluent.Kafka;
namespace Projections;
public sealed class OrdersConsumer(
IOrderProjection projection,
IProducer<string, string> dltProducer,
ILogger<OrdersConsumer> logger) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Task.Factory.StartNew(() => Run(stoppingToken), stoppingToken,
TaskCreationOptions.LongRunning, TaskScheduler.Default); // Consume is blocking: own thread
private void Run(CancellationToken ct)
{
var config = new ConsumerConfig
{
BootstrapServers = "localhost:9092",
GroupId = "order-projection",
AutoOffsetReset = AutoOffsetReset.Earliest,
EnableAutoCommit = true, // background commit of *stored* offsets
EnableAutoOffsetStore = false, // we store only after processing => at-least-once
PartitionAssignmentStrategy = PartitionAssignmentStrategy.CooperativeSticky,
MaxPollIntervalMs = 300_000
};
using var consumer = new ConsumerBuilder<string, string>(config)
.SetPartitionsRevokedHandler((c, partitions) =>
{
try { c.Commit(); } // flush stored offsets before losing the partitions
catch (KafkaException ex) { logger.LogWarning(ex, "Commit on revoke failed"); }
})
.Build();
consumer.Subscribe("orders");
try
{
while (!ct.IsCancellationRequested)
{
ConsumeResult<string, string> result = consumer.Consume(ct);
ProcessWithDeadLetter(result, ct);
consumer.StoreOffset(result); // marks this record done; committed within 5 s
}
}
catch (OperationCanceledException) { }
finally
{
consumer.Close(); // commits stored offsets and leaves the group cleanly
}
}
private void ProcessWithDeadLetter(ConsumeResult<string, string> r, CancellationToken ct)
{
for (int attempt = 1; ; attempt++)
{
try
{
// Idempotent: upsert keyed by order id, guarded by the event version.
projection.ApplyAsync(r.Message.Key, r.Message.Value, ct).GetAwaiter().GetResult();
return;
}
catch (Exception ex) when (attempt < 3 && ex is not FormatException)
{
Thread.Sleep(TimeSpan.FromMilliseconds(200 * attempt)); // short, bounded: keep the poll loop alive
}
catch (Exception ex)
{
logger.LogError(ex, "Dead-lettering {TopicPartitionOffset}", r.TopicPartitionOffset);
var headers = new Headers
{
{ "x-error", Encoding.UTF8.GetBytes(ex.GetType().Name) },
{ "x-source", Encoding.UTF8.GetBytes(r.TopicPartitionOffset.ToString()) }
};
dltProducer.Produce("orders.dlt",
new Message<string, string> { Key = r.Message.Key, Value = r.Message.Value, Headers = headers });
dltProducer.Flush(ct); // must be durable before we move the offset past it
return;
}
}
}
}
public interface IOrderProjection
{
Task ApplyAsync(string orderId, string json, CancellationToken ct);
}
EnableAutoOffsetStore = false and StoreOffset after processing.max.poll.interval.ms evicts the consumer and triggers rebalances that replay records. Instead: keep handlers fast, batch I/O, or pause partitions while work completes.ProduceAsync per message as high throughput. Why it is wrong: awaiting each send serialises the producer. Instead: use Produce with a delivery handler and let batching work.Kafka moves responsibility from the broker to the consumer. That buys throughput, replay and many independent readers, and costs you per-record retry, DLQ, delay and the discipline of offset management. I only reach for it when I need those benefits; for command processing on Azure, Service Bus is usually less code and fewer incidents.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| StoreOffset + auto commit | Most consumers | Duplicates on crash or rebalance | Never really wrong |
| Manual Commit per batch | Need explicit control, batch DB writes | Latency per commit | Per-record commits at high volume |
| Offsets stored in your DB | Single DB sink, want effectively-once | Seek logic on assignment | Many sinks |
| Kafka transactions | Kafka-to-Kafka stream processing | Throughput and complexity | External side effects |
Measure lag per partition (Kafka exporter, Confluent metrics or Azure Monitor for Event Hubs), rebalance count per hour, handler p99 against max.poll.interval.ms, and dead-letter topic rate. Lag on one partition only means a hot key; lag everywhere means the handler or the sink.
Global ordering means one consumer processing one message at a time, which kills throughput, so real systems guarantee order per key: per order, customer or account.
SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.MessageGroupId works like a session.Order breaks with competing consumers, retries, dead-lettering and rebalances. Better still, design so order doesn't matter: version numbers with "ignore older", events that carry full state, or commutative updates. The trade-off is that per-key order lets one stuck message block every later message for that key.
At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.
Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".
What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.
Service Bus, RabbitMQ and SQS are queue brokers: a message is delivered, settled and gone. Kafka is a partitioned, retained log: messages stay for the retention period and each consumer group tracks an offset, so you can replay.
For a .NET system on Azure doing commands and business events, I default to Service Bus. I pick Kafka when I need high-volume streaming and replay. The trade-off is features and simplicity versus throughput and history.
How to tell it (STAR)
**S:** Our order history page [at company] was showing data more than [20] minutes old because the projection consumer's lag hit [4 million]. **T:** I had to clear the lag and stop it recurring. **A:** Lag was on every partition, and the logs showed constant rebalances. A slow geocoding call made the poll loop exceed the 300-second limit, so the broker kept evicting consumers. I cached geocodes as a quick fix, then added per-key parallel processing with safe offset tracking, cooperative-sticky assignment and static membership. **R:** Throughput went from [3,000 to 9,000] records per second, rebalances dropped to zero, and lag stayed under [5,000] even at peak.
Last updated 23 Nov 2026.