Video in progress

Strong Junior 🧩 Microservices

When does Kafka preserve message order, and when does it break?

Order is guaranteed only inside a single partition. If messages belonging to one object (say, one order) are sent with the same key, they land in one partition and are read in order; with no key or with different keys there's no ordering guarantee.

📖 Answer

A topic consists of several partitions. The producer places a message into a partition by the hash of the key:

// all events of the order land in one partition
kafkaTemplate.send("order-events", order.getId().toString(), event);

If the key is null, messages are spread across partitions, and OrderCreated can land in one partition and OrderCancelled in another. If two different consumers process them in reverse order, the cancelled order goes back to the "created" state.

Cases that break order even inside a single partition:

  • producer retry: if the idempotent producer is off and max.in.flight.requests.per.connection > 1, a resent message can be written after the next one. In modern Kafka clients enable.idempotence=true is the default, which closes this problem;
  • increasing the partition count: the key's hash starts landing in a different partition, and old and new messages end up in two places;
  • parallel processing inside the consumer: if you read from one partition and hand the messages to a thread pool, you break the order yourself.

If you need global order across the whole topic, only a single partition is left, which kills parallelism. That's why "order per object" is usually enough and the key is chosen carefully.