DEV Community

designbench.dev
designbench.dev

Posted on Originally published at designbench.dev

Kafka partitions for system design interviews: keys, ordering, consumer groups and when to commit

The interview question: "Your order service publishes events to Kafka. Events for one account must be processed in order, but you also need to process thousands per second. How do you design the topic?"

This is where Kafka answers fall apart: candidates know the words (topic, partition, consumer group) but not the guarantees each one gives. Here is the walkthrough, round by round, with the simulations from the Designbench Kafka partitions lesson.

Round 1: Where ordering comes from

Interviewer: Does Kafka guarantee order?

You: Only within a partition. A topic is split into partitions; each partition is an append-only log read in order by exactly one consumer in a group. Across partitions there is no order at all. So the real design question is: which messages must share a partition?

Round 2: The key decides

Interviewer: So how do you keep one account's events in order?

You: Use the account ID as the message key. The default partitioner sends a key to hash(key) % partitions, so every event for one account lands in the same partition and is read in order, while other accounts run in parallel on other partitions.

Take account A sending events 1 to 12:

  • 1 partition, 1 consumer: in order, but the whole topic runs on one consumer.
  • 4 partitions, keyed by account: A's events stay in order, and other accounts run on the other 3 partitions in parallel.
  • 4 partitions, no key: fastest spread, but A's events race through 4 consumers and arrive as 4, 2, 3, 8, 1, 6, 12...

Ordering vs parallelism on Designbench
Ordering vs parallelism on Designbench: the key decides which events stay in order.

Round 3: How many partitions?

Interviewer: How do you pick the partition count?

You: Partitions cap your parallelism: a consumer group can have at most one active consumer per partition, and extra consumers sit idle. So I size from throughput. If I need 6,000 events a second and one consumer handles about 1,000, I need at least 6 partitions, and I'd start with 12 for headroom.

Why headroom up front? Because adding partitions later remaps keys. With hash % N, going from 6 to 8 partitions sends about 74% of keys to a different partition. Events for an account can then be processed in a new partition before older ones finish in the old one, which breaks ordering during the change.

Round 4: Producer settings that matter

Interviewer: Show me the producer.

Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
p.put(ProducerConfig.ACKS_CONFIG, "all");                // wait for the in-sync replicas
p.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);   // retries can't duplicate or reorder
p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

try (KafkaProducer<String, String> producer = new KafkaProducer<>(p)) {
    producer.send(new ProducerRecord<>("orders", accountId, eventJson)); // key = account
}
Enter fullscreen mode Exit fullscreen mode

Two settings to explain:

  • acks=all with a topic replication factor of 3 and min.insync.replicas=2: a write is acknowledged only once at least 2 replicas have it, so losing the leader doesn't lose acknowledged events. With acks=1, a leader that dies right after acknowledging can take the event with it.
  • Idempotent producer: without it, a retry after a lost acknowledgement can write the same event twice, or write it after a later one. Idempotence gives each batch a sequence number so the broker drops duplicates and keeps order. It is on by default in recent Kafka clients, but say it anyway.

Round 5: When to commit

Interviewer: The consumer reads offset 42, "charge $30", and crashes. What happens?

You: It depends on when it committed:

  • Commit, then process: the offset says 42 is done, but the charge never happened. The event is lost (at most once).
  • Process, then commit: the charge happened but the commit didn't, so after restart it reads 42 again and charges twice (at least once).
  • Process idempotently, then commit: the second attempt is recognised as a duplicate and skipped. Effectively once.
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

while (running) {
    ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(500));
    for (ConsumerRecord<String, String> r : batch) {
        payments.applyOnce(eventId(r), r.value());   // dedupe by event ID in the same DB transaction
    }
    consumer.commitSync();                           // only after the work is done
}
Enter fullscreen mode Exit fullscreen mode

That combination, at-least-once delivery plus idempotent processing, is what people mean by "exactly once" in practice. More in Message queues and Timeouts, retries and idempotency.

Round 6: The hot key

Interviewer: One account sends 60% of all traffic. Now what?

You: Its partition becomes the bottleneck, and its consumer's lag grows while the others idle. Options, in order of preference:

  • Check whether the hot account really needs total ordering. Often only per-order ordering matters, so key by order ID instead.
  • Split the hot key into sub-keys (account#0 to account#7) where ordering within each sub-stream is enough.
  • Give that tenant its own topic and consumers.

Always watch consumer lag per partition; it tells you about hot keys long before users do. See Observability.

Say it in the interview

"Kafka only orders within a partition, so I key by the entity that needs ordering, here the account ID. I size partitions from throughput with headroom, because consumers can't exceed partitions and adding partitions later remaps about three quarters of the keys. Producers use acks=all with min.insync.replicas=2 and idempotence on. Consumers commit after processing and dedupe by event ID, which gives effectively-once results. I'd monitor lag per partition to catch hot keys."

Common mistakes

  • Claiming Kafka guarantees order across a whole topic.
  • Sending events without a key, then wondering why they arrive out of order.
  • Running more consumers than partitions and expecting more throughput.
  • Adding partitions to a keyed topic without planning for the reshuffle.
  • acks=1 for events you can't afford to lose.
  • Auto-committing offsets before the work is done.

Practise it

Change partitions and consumers, add a hot account, crash a consumer and kill a leader in the Kafka partitions lesson on Designbench. Related: Message queues, Replication and Consistent hashing.

Top comments (0)