📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Explain Kafka for a .NET engineer: topics and partitions, consumer groups, offsets and commits, and rebalancing. What causes consumer lag, how do you commit offsets safely with Confluent.Kafka, and what delivery guarantee does your consumer end up with?

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.

Senior Theory Advanced confluent-kafka consumer-groups distributed-systems kafka messaging offsets

🎯 Key points

  • Topic = partitioned append-only log written by many producers and read by many groups at once; order per partition only
  • Retention by time or size, or log compaction, which keeps only the latest record per key (null value = tombstone)
  • Consumer group: each partition assigned to one member; members beyond partition count sit idle
  • Default Confluent.Kafka settings store offsets on consume and auto-commit every 5 s, so a crash can skip unprocessed records
  • Safe pattern: EnableAutoOffsetStore = false, StoreOffset after processing, auto commit in background (or Commit per batch) = at-least-once, so handlers are idempotent
  • Rebalancing: joins, leaves, crashes or exceeding max.poll.interval.ms; cooperative-sticky and static membership (GroupInstanceId) reduce pauses
  • Lag = log end offset minus committed offset per partition; monitor with kafka-consumer-groups, a Kafka/Prometheus exporter or Confluent/Event Hubs metrics
  • Poison records block a partition: no built-in DLQ, so route to a dead-letter topic after bounded retries

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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_offsets topic, 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 Consume returns, so a crash can commit records you never finished: at-most-once by accident. I set EnableAutoOffsetStore = false and call StoreOffset only 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."


Core vocabulary

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

Commit strategies in Confluent.Kafka

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

What drives lag

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate understands Kafka's log model and can run a consumer that neither loses records nor drowns in rebalances.

Green flags

  • Explains partitions as the unit of order and parallelism
  • Knows the default offset store behaviour and the StoreOffset-after-processing pattern
  • Describes rebalance triggers and cooperative-sticky / static membership
  • Has a plan for poison records (dead-letter topic)

Red flags

  • Thinks reading a record deletes it
  • Expects more consumers than partitions to help
  • Assumes Kafka provides exactly-once into a database

📚 Learn in depth

1. The log model

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.

2. Partition assignment and rebalancing

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.

  • Eager protocols (range, round-robin) revoke all partitions from everyone, then reassign: a stop-the-world pause.
  • Cooperative-sticky (PartitionAssignmentStrategy.CooperativeSticky) only moves the partitions that need to move, in incremental rounds.
  • Static membership (GroupInstanceId) lets a restarting pod rejoin without a rebalance within the session timeout; useful for rolling deploys.
  • Kafka 4.x brings the new consumer group protocol (KIP-848) with server-side assignment; check client support in your Confluent.Kafka version before relying on it.

Handle SetPartitionsRevokedHandler to commit stored offsets for partitions you're about to lose.

3. Offsets and commits

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.

4. Delivery semantics

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).

5. Poison records and retries

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.

6. Producer side

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.

7. Running Kafka from .NET on Azure

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.

Try it yourself

  1. Run a single-node Kafka (KRaft) in Docker; create a 6-partition topic and produce 100,000 keyed records.
  2. Start 3 then 8 consumers in one group; observe assignment and idle members.
  3. Use kafka-consumer-groups --describe to watch lag per partition while a consumer sleeps 50 ms per record.
  4. Kill a consumer after processing but before committing; count replayed records.
  5. Make the handler sleep longer than max.poll.interval.ms; observe the rebalance and duplicate processing; switch to cooperative-sticky and compare.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Keeping Confluent.Kafka's default offset store with long processing. Why it is wrong: offsets are stored on consume and auto-committed, so a crash skips unprocessed records. Instead: set EnableAutoOffsetStore = false and StoreOffset after processing.
  • Mistake: More consumers than partitions. Why it is wrong: extra members sit idle; throughput doesn't increase. Instead: plan partition count for peak parallelism.
  • Mistake: Slow or blocking work in the poll loop. Why it is wrong: exceeding 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.
  • Mistake: Committing out of order when processing a partition in parallel. Why it is wrong: a crash skips records that hadn't finished. Instead: commit only the lowest contiguous completed offset.
  • Mistake: Expecting a built-in DLQ or per-record retry. Why it is wrong: a poison record blocks its partition forever. Instead: bounded retries, then a dead-letter topic with error headers.
  • Mistake: Adding partitions to an ordered topic in production. Why it is wrong: keys remap and per-key order breaks. Instead: create a new topic and migrate.
  • Mistake: Treating 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says order holds within a partition Why: Checks they can design ordering per key and know what breaks it
    How to answer

    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.

    • Service Bus: set SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.
    • Kafka: the message key picks the partition, and order holds within it. Adding partitions remaps keys.
    • SQS FIFO: the 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.

  2. When: Candidate mentions Kafka exactly-once semantics Why: Checks they know EOS stops at the Kafka boundary
    How to answer

    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".

    • Kafka transactions give exactly-once only for read-process-write within Kafka.
    • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

    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.

  3. When: Candidate contrasts Kafka with a queue broker Why: Checks they can choose between Kafka and Service Bus for a workload
    How to answer

    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.

    • Ordering: Service Bus sessions, SQS FIFO message groups, Kafka per partition; RabbitMQ only per queue with a single consumer.
    • Guarantees: all are at-least-once in practice, so consumers deduplicate.
    • Operations: Service Bus and SQS are fully managed; RabbitMQ and self-hosted Kafka need a team (or Confluent Cloud / Event Hubs' Kafka endpoint).

    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.

🛠 Real-world problems: how you handle them

Rebalance storm drives consumer lag to millions
Situation
An order-projection consumer group reads a [12]-partition topic on [Confluent Cloud in Australia East], normally [3,000] records per second, feeding a customer-facing order history page.
Signals
Consumer lag alert above [1 million]; logs full of partitions revoked and assigned every few minutes; duplicate updates in the projection; order history page showing data [20+ minutes] stale.
Investigation
Lag per partition showed all partitions affected (not a hot key); consumer logs showed `MaxPollExceeded` errors; Application Insights traces showed an 800 ms p95 geocoding HTTP call per record, so a burst of slow calls exceeded the 300 s poll interval; `kafka-consumer-groups --describe` confirmed members cycling.
Resolution
Immediate: increased `max.poll.interval.ms` and cached geocode results to shorten processing. Real fix: per-key parallelism inside each partition with lowest-contiguous offset tracking, cooperative-sticky assignment and static membership for rolling deploys.
Prevention
Alert on rebalance rate and on handler p99 approaching the poll interval; load test with dependency latency injected; dashboard of lag per partition; runbook for lag incidents.

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.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me