Skip to the page

Kafka · core

Kafka topics, partitions, keys and ordering

A topic is split into partitions. Kafka keeps order only inside one partition, so the message key decides what stays in order. Good topic design starts from keys, retention and readers.

The notes

What you must know

  • Kafka keeps order only inside one partition, not across a topic.
  • The default partitioner hashes the key (murmur2) and takes the result modulo the partition count, so one key always goes to one partition. Records without a key are spread in batches.
  • Use the order id as the key for order events, so one order's events stay in order. A random or timestamp key spreads one order over many partitions.
  • Adding partitions later changes which partition a key maps to, so ordering breaks across the change. Plan the partition count for throughput, consumer parallelism and some headroom.
  • Two services writing events for the same order cannot be ordered by Kafka. Put a per-order sequence or version in the event, set by one owner, and let consumers ignore older versions.
  • Separate topics when retention, volume or readers differ. Not one topic per city (city is a field) and not one per restaurant or order.
  • Keying by a value with a very big owner (one huge cloud kitchen) creates a hot partition.
  • Each reader service has its own consumer group, so each one gets every event.

The red pen

Common traps: mistake → fix

  • Mistake: Kafka keeps global order

    Fix: only per partition.

  • Mistake: Set max.in.flight to 1 as the only fix for order

    Fix: the idempotent producer already keeps order, and one in flight is slow.

  • Mistake: Key rider pings by city

    Fix: one city becomes a hot partition; key by rider id.

  • Mistake: Compact the order event stream

    Fix: compaction would delete the history that replay needs.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why do events for one order arrive out of order?
  2. What should the key be for order events, and why?
  3. What happens to ordering if you add partitions?
  4. Design the topics for orders, rider pings and menu changes.

Practise

Practise with these questions

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