Skip to the page

Design building blocks · mid

Kafka partitions, consumer groups and lag

A topic is split into partitions. Inside a group each partition is read by one consumer, so parallelism equals the partition count. Lag grows when consumers are too few, skewed, stuck or slow.

The notes

What you must know

  • A topic is split into partitions. Each is an ordered append-only log with one leader and follower replicas. The producer picks the partition by hashing the key; keyless messages spread across partitions.
  • In a consumer group each partition is read by one consumer. Consumers beyond the partition count sit idle.
  • Offsets are committed to an internal topic. Commit after processing gives at-least-once (duplicates possible, so consumers must be idempotent). Commit before gives at-most-once.
  • Durability: replication factor 3, acks=all and min.insync.replicas=2 survive losing one broker without losing data. The idempotent producer is on by default.
  • Exactly-once with the idempotent producer plus transactions covers read-process-write inside Kafka. Writes to an external database still need their own idempotency.
  • Lag checks: per partition, consumers against partitions, time per message, errors and restarts, rebalances, and the latency of what the consumer calls.
  • Causes of lag: hot key or bad key choice fills one partition (fix the key); a poison message means no commit and a restart loop (retry topic, then dead-letter); a slow downstream (batch, or bounded async concurrency keeping per-key order).
  • More partitions change the key to partition mapping, so ordering breaks during the switch. Plan it. Alert on lag in time, not only message count. Do not delete the consumer group to reset it.

The red pen

Common traps: mistake → fix

  • Mistake: Add consumers to fix lag

    Fix: not beyond the partition count.

  • Mistake: Kafka orders across partitions

    Fix: only inside one.

  • Mistake: Exactly-once covers my database writes

    Fix: it does not.

  • Mistake: Skipping messages is a fix

    Fix: record them in a dead-letter topic.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do partitions and consumer groups work?
  2. What delivery guarantee do you get and how do you get exactly-once?
  3. Consumer lag keeps growing during a sale. What do you check?
  4. What happens when you add partitions?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview