You have a Kafka topic with multiple partitions, and you need to ensure that messages with the same key are processed in the order they were sent. How do you achieve this?

Preserving processing order for related messages in a multi-partition topic relies on Kafka's guarantee that all records sharing the same key are always routed to the same partition, and within a partition, order is strictly preserved.

Key Points: • The default partitioner hashes the record key to deterministically pick a partition, so the same key always maps to the same partition as long as the partition count doesn't change. • Kafka only guarantees ordering within a single partition, never across partitions. • Choosing a good key (e.g. customer ID, order ID) is critical — an evenly distributed key avoids hot partitions while still keeping related events together. • Adding partitions to an existing topic can break this guarantee going forward, since the key-to-partition mapping can shift.

Example: Tagging every event for a given order with the order ID as the record key guarantees all of that order's events (created, paid, shipped) land on the same partition and are read by the consumer in the exact sequence they were produced.

Code Example:

producer.send(new ProducerRecord<>("orders", orderId, orderEventJson));

Interview Tip: A concise interview answer is:

"I'd set the order-relevant identifier as the record key, since Kafka's default partitioner hashes the key to always route it to the same partition, and Kafka guarantees strict ordering within a partition, which together give me ordered processing for all messages sharing that key."