Junior — Middle
What methods can be used to ensure the preservation of message order in Kafka?
sobes.tech AI
Answer from AI
In Apache Kafka, message order is guaranteed within a single partition. To ensure message order preservation, the following approaches can be used:
- Use a single partition for a topic — then all messages go to one partition, and order is maintained.
- Use a key when sending messages — Kafka guarantees the order of messages with the same key within a partition. Thus, if messages with the same key always go to the same partition, the order for that key is preserved.
- Configure partitioning so that related messages go to the same partition — for example, implement a custom partitioner that distributes messages across partitions based on the key.
Example of sending a message with a key in Java:
ProducerRecord<String, String> record = new ProducerRecord<>("topic", "key1", "message1");
producer.send(record);
Thus, the message order with the key "key1" will be preserved within a single partition.